【问题标题】:Angular directive: whats the difference between scope in controller vs scope in link function?Angular 指令:控制器中的范围与链接功能中的范围有什么区别?
【发布时间】:2017-01-21 10:48:09
【问题描述】:

我正在学习 Angular directives,但我无法围绕 scope 主题。假设我有这个名为parentDirective 的自定义directive。它有一个controller 属性和一个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>

我可以通过$scope 变量在controller 函数中获取character 对象,并且我可以通过scope 访问link 函数中的相同数据。这两种方法在这方面有什么区别?第二个问题,是否可以将click 绑定到directive 并获得这样的对象:

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

【问题讨论】:

  • 没有区别。这是同一个对象。

标签: javascript angularjs angularjs-directive angular-directive


【解决方案1】:

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

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

事件处理程序与任何其他函数没有区别,它是

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

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

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

那么指令可能看起来像

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,但这里不需要。

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 1970-01-01
    • 2015-10-12
    • 2014-12-22
    • 2013-05-28
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多