在angularJS中,我们可以使用Directives来访问元素,我们可以使用这些指令设置属性。我想在不使用Directives的情况下获取/设置DOM元素的一些属性。
<div class=main ng-app="myApp" ng-controller="SalesController">
<div class=ele1> </div>
<div class=ele2> </div>
<div class=ele3></div>
</div>
在某些地方,我希望某些元素的高度可以进行一些计算:
var myApp = angular.module('myApp', []);
myApp.controller('SalesController',function($scope){
//this code not working
document.getElementsByClassName("ele1").clientHeight;
});
我知道如何通过使用指令来获得高度,但在某些情况下,我们需要在项目的不同部分中使用div元素的高度/宽度,每次添加指令都会增加代码。
是否有单行方式在angularjs中找到div的高度/宽度(如jquery中的$("classname").height()
)?我宁愿不使用jQuery也这样做。
答案 0 :(得分:1)
您可以使用JavaScript循环找到height/width
个DOM
元素。
示例:强>
var myApp = angular.module('myApp', []);
myApp.controller('SalesController',function($scope){
var objects = document.getElementsByClassName('YOUR_CLASS_NAME');
var height = 0;
for(var i=0;i<objects.length;i++){
height = objects[i].clientHeight;
console.log(height); /*Output in JS console*/
alert(height); /*Output in window alert Box*/
}
});
注意: document.getElementsByClassName()
函数返回对象数组。
document.getElementById()
返回单个Object。您不能直接在对象数组选择器中使用clientHeight
属性。因为clientHeight
是一个对象属性。
其他一些JavaScript DOM选择器功能
document.getElementById() /*Return single Object*/
document.getElementsByTagName() /*Return Object Array*/
document.getElementsByTagNameNS()
document.getElementsByName()
document.querySelector()
document.querySelectorAll()
....
答案 1 :(得分:1)
我们可以使用javascript或角度js访问元素。在上面的回答中,他们使用javascript来访问元素。在角度js中,我们可以在控制器中注入$元素,我们可以通过使用类或者访问任何元素ID
myApp.controller('SalesController',function($scope,$element){
//here we are using 2 indexes but that is not the position index of child elements
var temp=$element[0].getElementsByClassName('ele1')[0].clientHeight;
});