Skip to content Skip to sidebar Skip to footer

Alternative Of 'getelementbyid' In Angularjs

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(

Solution 1:

Use only

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

Solution 2:

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:

<ulmy-menu-list="output"ng-style="myStyle"><ling-repeat="item in items"><ahref="#">{{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>

Solution 3:

Use query selector

 angular.element( document.querySelector( '#id' ) );

Solution 4:

While the other answers might be correct on the alternative of getElementById, your code should be rewritten in the Angular-way. See this plunker.

It should reflect your requirements anyway.

Post a Comment for "Alternative Of 'getelementbyid' In Angularjs"