我在同一页面上有两个指令,但在不同的元素上。 类似的东西:
<div directive-one>
<div directive-two></div>
</div>
在 directiveOne 中,我创建了一些变量(比方说,$scope.pageConfig.variable
)。
我希望 directiveTwo 使用这个变量。
问题 - directiveOne 并不总是在 directiveTwo 之前加载。
问题是 - 有没有办法确保 directiveOne 在 directiveTwo 之前加载,以便该变量可用于 directiveTwo?
谢谢:)
更新: 我发现答案应该是像这样在 directiveOne 中使用 Controller :
return {
controller: function($scope){ $scope.variable = variable; },
link : ...
}
问题是我以这种方式使用时出现错误 [$injector: unpr]。这应该解决我的问题吗?知道为什么这会给我带来错误吗?
最佳答案
如何在指令 B 中要求指令 A:
var myApp = angular.module('myapp', [])
.run(function(){
});
myApp.directive('fooDirective', function() {
return {
restrict: 'A',
controller: function(){
this.pageConfig = {
someVaraible: 'value from foo'
};
}
}
});
myApp.directive('barDirective', function() {
return {
restrict: 'A',
require: '^fooDirective',
link: function(scope, element, attr, fooDirectiveController){
console.log(fooDirectiveController.pageConfig);
}
}
});
这是一个 Plunk更多information关于扩展指令,这里是some more info
关于javascript - Angularjs:指令加载顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24889628/