查找元素的位置-angularjs
我试图找到任意元素在角度指令中的位置 我的想法是使用ng类添加一个类,然后使用查找元素的位置-angularjs,angularjs,Angularjs,我试图找到任意元素在角度指令中的位置 我的想法是使用ng类添加一个类,然后使用元素[0].querySelector('.theClass').getBoundingClientRect()以获取该位置 错误为:无法读取null的属性“getBoundingClientRect” 因此,我的怀疑是,指令的模板尚未编译,因此querySelector无法找到它 因此,我也尝试了$timeout(function(){…}),但结果相同 你知道如何找到角坐标中任意元素的位置吗 守则: 'use st
元素[0].querySelector('.theClass').getBoundingClientRect()代码>以获取该位置
错误为:无法读取null的属性“getBoundingClientRect”
因此,我的怀疑是,指令的模板尚未编译,因此querySelector无法找到它
因此,我也尝试了$timeout(function(){…})
,但结果相同
你知道如何找到角坐标中任意元素的位置吗
守则:
'use strict';
angular.module('myApp')
.directive('myDirective', function ($timeout) {
return {
templateUrl: 'the/template',
restrict: 'EA',
scope: {
objects:"="
},
link: function (scope, element, attrs) {
$timeout(function(){
//DOM has finished rendering
var rect = element[0].querySelector('.theClass').getBoundingClientRect();
console.log('this is the element');
console.log(rect.top, rect.right, rect.bottom, rect.left);
});
}
};
});
模板是关于:
<span ng-repeat="object in objects">
<span ng-class="{'theClass':$last}"></span>
</span>
也许你应该试着把它放到postLink中,比如:
angular.module('myApp')
.directive('myDirective', function () {
return {
templateUrl: 'the/template',
restrict: 'EA',
scope: {
objects:"="
},
link: {
post : function (scope, element, attrs) {
var rect = element[0].querySelector('.theClass').getBoundingClientRect();
console.log('this is the element');
console.log(rect.top, rect.right, rect.bottom, rect.left);
}
}
};
});
你能发布指令的代码吗?我添加了一些代码。希望它是正确的,因为我删除了所有东西,除了有问题的代码,我没有意识到这一点。默认值是pre?但它给出了同样的结果。