Check this PLNKR, i have one list with id myMenuList
, this id am accessing in script.js
to display Numer of li
and UL width
by $scope.mml = angular.element(document.getElementById('myMenuList'));
.
But as per requirement I should not be accessing it in controller like this. Is there any alternative we can do by keeping the same behaviour?
HTML CODE
<div class="menucontainer left">
<ul id="myMenuList" ng-style="myStyle">
<li ng-repeat="item in items"> <a href="#">{{item.name}}</a> </li>
</ul>
</div>
JavaScript
$scope.mml = angular.element(document.getElementById('myMenuList'));
$timeout(function() {
$scope.numerofli = $scope.mml.find('li').length;
$scope.ulwidth = $scope.mml[0].clientWidth;
}, 1000);
A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.
You can use document. getElementById() in Angularjs, but manipulating HTML in a controller is not a good practice.
To use the document. getElementById() method in TypeScript: Use a type assertion to type the selected element correctly. Use a type guard to make sure the variable does not store a null value.
To examine the scope in the debugger: Right click on the element of interest in your browser and select 'inspect element'. You should see the browser debugger with the element you clicked on highlighted. The debugger allows you to access the currently selected element in the console as $0 variable.
Use only
var ele = angular.element('#id');
var ulwidth = ele[0].clientWidth;
Demo Plunker
Implement a directive with isolated scope to encourage modularity and re-use:
app.directive('myMenuList', function($timeout) {
return {
restrict: 'A',
scope: {
myMenuList: '='
},
link:function($scope, $element, $attr) {
$timeout(function(){
$scope.myMenuList.numerofli= $element.find('li').length ;
$scope.myMenuList.ulwidth= $element[0].clientWidth;
}, 1000);
}
}
});
To use it, initialize an output model from inside your parent controller:
app.controller('scrollController', function($scope, $timeout) {
$scope.output = {};
...
});
Place the my-menu-list
attribute on the ul
element, and pass it the model defined earlier:
<ul my-menu-list="output" ng-style="myStyle">
<li ng-repeat="item in items"> <a href="#">{{item.name}}</a>
</li>
</ul>
When the directive executes it will populate the model with two properties, which you can then reference in your HTML:
<p><b>Numer of 'li': {{output.numerofli}}</b></p>
<p><b>Width: {{output.ulwidth}}</b></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With