【发布时间】:2016-06-17 22:57:15
【问题描述】:
我正在尝试访问指令链接功能中的 DOM 元素。该元素位于 another 指令的视图中。代码如下:
第一个指令
(function () {
'use strict';
angular.module("testAPP",[])
.directive('firstDirective', function(){
var directive = {
restrict: 'E',
templateUrl: 'firstDirective.html'
}
return directive;
})
})();
第二条指令
(function () {
'use strict';
angular.module("testAPP",[])
.directive('anotherDirective', function(){
var directive = {
restrict: 'E',
templateUrl: 'anotherDirective.html',
link: function($scope){
//element from another directive's view
var height = document.getElementByClassName("sky")[0].offsetHeight;
}
};
return directive;
});
})();
有一个控制台错误提示 height 变量未定义。 我尝试了超时功能,这对我有用,但我认为这不是一个好的解决方案:
setTimeout(function(){
var height = document.getElementByClassName("sky")[0].offsetHeight;
console.log(height);
});
我也尝试了“require”,但它导致找不到指令的错误(我认为这可能是因为指令位于不同的目录中)
那么,你能告诉我 require 不起作用的原因,并建议我比 timeout 更好的解决方案
【问题讨论】:
-
这是您在问题中提到的另一个指令,我只看到一个指令是 test-app
-
它们是在另一个内部使用的吗..?
-
不,这些指令位于不同的文件中
标签: javascript angularjs