javascript - 如何在指令 AngularJS 之间传递对象?

标签 javascript angularjs angularjs-directive angularjs-scope

如果我在指令 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"
    }
})

Working example .

关于javascript - 如何在指令 AngularJS 之间传递对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18628314/

相关文章:

AngularJS:指令范围没有被调用 $destroy

javascript - 如何在d3 xhr发送请求中指定超时

javascript - 异步自动 : stop entire chain after first error

angularjs - Angular 搜索JSON中的值并显示相应的数据

javascript - 使用 Angular JS 将父 div 的焦点更改为子 href 元素的焦点

javascript - Angular-bootstrap 弹出窗口需要工具提示模块吗?

angularjs - 带有 ui-select 的 Angular 组合框

javascript - 在 AngularJS 中按数组长度或嵌套对象属性进行过滤

javascript - 对Python和Javascript的理解只是很基础?

angularjs - 如何在 ng-repeat 中分隔组