javascript - Angular Directive(指令) : whats the difference between scope in controller vs scope in link function?

标签 javascript angularjs angularjs-directive angular-directive

我正在学习 Angular directive我无法理解 scope话题。假设我有这个自定义directive其名称为parentDirective 。它有一个controller属性(property)和link属性,如下:

angular.module("app").directive("parentDirective", function () {
    return {
        restrict: "E",
        templateUrl: "dirs/parent.html",
        scope:{
            character: "="
        },
        controller: function ($scope) {
            $scope.getData = function (data) {
                console.log(data);
            }
        },
        link: function (scope,elem, attrs) {
            elem.bind("click", function (e) {
                //get object here?
            });
            scope.getData = function (data) {
                console.log(data);
            }
        }
    }
});

其模板定义如下:

<p ng-click="getData(character)">
    {{character.name}}
</p>

我可以获得character controller 中的对象通过$scope功能变量和我可以访问 link 中的相同数据功能通过scope 。这两种方法在这方面有什么区别?第二个问题,是否可以绑定(bind)clickdirective并获取这样的对象:

    elem.bind("click", function (e) {
        //get object here?
    });

最佳答案

作用域特定于当前指令实例,并且在两个函数中是同一对象。

对于在作用域上定义方法,如果在 Controller 或链接函数中定义它们没有区别,除非存在竞争条件要求尽早定义方法。因此,在 Controller 中定义作用域方法是有意义的。

事件处理程序与任何其他函数没有什么不同,它是

elem.on("click", function (e) {
  scope.$apply(function () {
    scope.character...
  });
});

scope.$apply(...) 包装器无论如何都不会造成伤害,但它的必要性取决于 scope.character 发生的情况。

指令只能有controller而没有link。当前的 Angular 版本(1.5+)建议采用 bindToController + controllerAs 的样式使用而不是 scope 绑定(bind)作为指令和组件的共同基础。

那么指令可能看起来像

restrict: "E",
template: '<p>{{$ctrl.character.name}}</p>',
controllerAs: '$ctrl',
bindToController: { character: "=" },
controller: function ($element, $scope) {
    var self = this;

    self.getData = function (data) { ... };

    $element.on("click", function (e) {
        scope.$apply(function () {
            self.character...
        });
    });
}

link 函数可能显示为 $postLink controller hook ,但这里不需要。

关于javascript - Angular Directive(指令) : whats the difference between scope in controller vs scope in link function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41778436/

相关文章:

javascript - Angular - 服务器中的更改图像未反射(reflect)在 View 中

html - 如何在ionic 3中使用@output

angularjs - 如何获取目录分页过滤结果引用

javascript - xpath - 限制搜索到节点不工作?

javascript - 使用 jQuery 隐藏表行

angularjs - 手动安装 Selenium Server 以使用古巴的 Protractor (AngularJS)

javascript - 为什么我的 $timeout.cancel 在这里起作用,但在这里不起作用?

javascript - 特定用途的javascript解析器

javascript - 用零或增量初始化对象的更好方法是什么?

angularjs - Angular 指令 - 何时以及如何使用编译、 Controller 、预链接和后链接