Alternative to 'getElementById' in angularjs

Check PLNKR , I have one list with id myMenuList , this identifier is available in script.js to display Numer of li and UL width on $scope.mml = angular.element(document.getElementById('myMenuList')); . But on demand, I do not have to access it in the controller like this. Is there an alternative we can do by maintaining the same behavior?

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); 
+6
source share
4 answers

Demo plunker

Implement an isolated scope directive to encourage modularity and reuse:

 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 the output model from inside the parent controller:

 app.controller('scrollController', function($scope, $timeout) { $scope.output = {}; ... }); 

Put the my-menu-list attribute on the ul element and pass it the previously defined model:

  <ul my-menu-list="output" ng-style="myStyle"> <li ng-repeat="item in items"> <a href="#">{{item.name}}</a> </li> </ul> 

When executing the directive, it will populate the model with two properties that you can reference in your HTML:

 <p><b>Numer of 'li': {{output.numerofli}}</b></p> <p><b>Width: {{output.ulwidth}}</b></p> 
+6
source

Use only

  var ele = angular.element('#id'); var ulwidth = ele[0].clientWidth; 
+7
source

Use query selector

  angular.element( document.querySelector( '#id' ) ); 
+2
source

While other answers may be correct regarding the getElementById alternative, your code should be rewritten in Angular -way. See plunker .

In any case, it should reflect your requirements.

+1
source

Source: https://habr.com/ru/post/975012/


All Articles