我已将控制器与指令相关联:
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');
}
答案 0 :(得分:1)
您应该避免使用指令中的scope: {}
来访问控制器函数,因为指令中的scope: {}
会从控制器创建隔离范围。
这就是您无法从指令模板访问控制器功能的原因。
避免scope: {}
之后使用普通控制器函数等函数。
像:
<button data-ng-click="myFunction()">call my function</button>
您可以在指令的链接功能中使用范围。
link: function (scope, element, attrs)