在angularjs中的“getElementById”的替代 [英] alternative of 'getElementById' in angularjs
问题描述
请检查此 PLNKR ,我有一个ID为 myMenuList $ c的列表$ c>,此id在
script.js
中访问以显示数字li
和 UL width
由 $ scope.mml = angular.element(document.getElementById('myMenuList'));
。
但是根据需要,我不应该像这样在控制器中访问它。有没有任何替代方法,我们可以通过保持相同的行为?
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);
推荐答案
使用隔离范围实施指令以鼓励模块化和重用:
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 = {};
...
});
将 my-menu-list
属性在 ul
元素,并传递它之前定义的模型:
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>
当指令执行时,它将使用两个属性填充模型,然后您可以在HTML中引用:
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>
这篇关于在angularjs中的“getElementById”的替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!