angularjs - 在模板中使用指令 Controller 方法

标签 angularjs angularjs-directive angularjs-scope

假设我有这个指令:

app.directive('person', function() {
    return {
        restrict: 'E',
        controller: function($scope) {
            $scope.sayHi = function() {
                console.log('hi');
            }

            this.sayBye = function() {
                console.log('goodbye')
            }
        },
        link: function(scope, element, attrs) {

        },
        template: '<p ng-click="sayHi()">Hello</p>'
    }
});

如果元素被点击,sayHi() 将被调用,因为它附加到 $scope,但是 sayBye 方法行不通

我的问题:

  1. 是从模板调用 Controller 方法的唯一方式 通过将它附加到 $scope 来实现?

  2. 如果是这样,这不是运行 与其他指令功能发生冲突的风险 以相同的方式附加到范围还是每个指令都有自己的范围?

  3. 是附加的唯一原因 this 的方法允许其他指令访问这些方法 通过 require?

我假设最好尽可能封装指令逻辑,因此欢迎任何建议。

最佳答案

Is the only way to call a controller method from the template achieved by attaching it to the $scope?

是的。范围是模板和 JavaScript 之间的代理。

If so, doesn't this run the risk of colliding with other directive functions that could be also attached to the scope in the same way or does each directive have its own scope?

是的,存在这种风险,但范围的定义类似于父范围和子范围的树,第一个找到的范围(从当前范围向上搜索)适用。希望这个场景能解释我想说的:

  • 根范围
  • 名字=“强尼”
    • child
    • 名字=“珍妮”
      • 孙子
      • name = "乔纳斯"

当 grand child scope 附加到带有 {{ name }} 的模板时,结果将是 Jonas,类似地,当 child scope 附加到一个带有 {{ name }} 的模板,结果将是 Jenny

指令是否创建范围,由其 scope 属性决定。查看Angular documentation on directives有关详细信息。

Is the only reason to attach methods to this to allow other directives access to those methods via require?

确切地说,您正在传递一个构造函数,并通过使用 this.foo = function () {} 在实例上定义一个函数,并且该实例与需要它的每个人共享.作为旁注,请记住 this.foo = function () {}Foo.prototype.foo = function () {} 在性能敏感方面的区别情况!

关于angularjs - 在模板中使用指令 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18634637/

相关文章:

regex - Angular ng-pattern 不检查正则表达式的字符上限

angularjs - 如何更新状态变化指令

javascript - 从 ng-click 函数调用服务

javascript - 如何在 ng-repeat 过滤器中使用范围变量?

javascript - AngularJS ngRoute 抛出未捕获错误 : [$injector:modulerr]

javascript - 如何在angularjs中以编程方式调用自定义指令

javascript - 如何通过单击链接制作可扩展的表格?

javascript - Angular : How do optimize the below if/else statement in angularjs?

javascript - 从 Controller 观察工厂变量

angularjs-scope - ng-init + ng- Controller : strange behavior in the controller's scope