Html angularjs 中“getElementById”的替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25738234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
alternative of 'getElementById' in angularjs
提问by ankitd
Check this PLNKR, i have one list with id myMenuList, this id am accessing in script.jsto display Numer of liand UL widthby $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?
检查这个PLNKR,我有一个带有 id 的列表myMenuList,这个 id 正在访问script.js以显示Numer of li和UL width通过$scope.mml = angular.element(document.getElementById('myMenuList'));。但是根据要求,我不应该像这样在控制器中访问它。我们可以通过保持相同的行为来做任何其他选择吗?
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
JavaScript
$scope.mml = angular.element(document.getElementById('myMenuList'));
$timeout(function() {
$scope.numerofli = $scope.mml.find('li').length;
$scope.ulwidth = $scope.mml[0].clientWidth;
}, 1000);
回答by Shohel
Use only
仅使用
var ele = angular.element('#id');
var ulwidth = ele[0].clientWidth;
回答by pixelbits
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-listattribute on the ulelement, and pass it the model defined earlier:
将my-menu-list属性放在ul元素上,并将之前定义的模型传递给它:
<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:
当指令执行时,它将用两个属性填充模型,然后您可以在 HTML 中引用它们:
<p><b>Numer of 'li': {{output.numerofli}}</b></p>
<p><b>Width: {{output.ulwidth}}</b></p>
回答by cs1193
Use query selector
使用查询选择器
angular.element( document.querySelector( '#id' ) );

