如果我在指令 A 的链接函数内定义/实例化一个对象 foo
。从单独指令的链接函数访问同一对象的方法是什么?
最佳答案
引自documenation :
The controller is instantiated before the pre-linking phase and it is shared with other directives (see require attribute). This allows the directives to communicate with each other and augment each other's behavior.
这意味着要在同一对象或其子对象上的两个指令之间共享数据,您需要在指令 A Controller 内公开 foo,并在指令 B 中注入(inject) require
选项。
指令看起来像这样:
.directive("dirA", function () {
return {
controller: function ($scope, $element, $attrs) {
},
link: function ($scope, $element, $attrs, controller) {
controller.foo = $attrs.dirA;
}
}
})
.directive("dirB", function () {
return {
link: function ($scope, $el, $attr, controller) {
$scope.shared = controller.foo;
},
require: "dirA"
}
})
关于javascript - 如何在指令 AngularJS 之间传递对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18628314/