访问与指令实例关联的控制器

Accessing the controller associated with a directive instance

本文关键字:控制器 关联 实例 指令 访问      更新时间:2023-09-26

我将一个控制器与一个指令相关联,如下所示:

return function MyDirective() {
    return {
        scope: {},
        restrict: 'E',
        template: template,
        controller: 'myController',
        replace: true,
    };
};

如果我想从模板中访问控制器上的方法,我是否需要将控制器添加到作用域的属性中?

模板:

<div> 
  <div> 
    <button ng-click="doSomething()">Do something.</button>
  </div>
</div> 

控制器:

function MyController() {}
MyController.prototype.doSomething() {
  window.alert('foo');
}

你应该避免scope: {}从你的指令访问控制器功能,因为scope: {}在你的指令创建隔离范围从你的控制器。

这就是为什么你不能从指令模板中访问控制器函数。

避免scope: {}后使用像普通控制器功能一样的功能

:

<button data-ng-click="myFunction()">call my function</button>

你可以在指令的链接函数中使用scope

link: function (scope, element, attrs)