我已经编写了自己的指令,我想从该指令中调用父ng-controller上的方法。我尝试通过在我的指令中添加require:'ngController‘来做到这一点。然而,返回的控制器只是一个空对象。我运行的是1.4.8。
<div ng-controller="myController">
<div my-directive></div>
</div>
app.directive('myDirective', function() {
return {
restrict: 'A',
scope: false,
require: '^ngController',
link: function (scope, $element, attrs, controller) {
//controller is empty object..
};
}
});更新:我的错误在于我将一个方法添加到了控制器作用域,而我应该将它直接添加到控制器中。
app.controller('myController', function($scope) {
$scope.myMethod = function() {}; //Not callable from controller passed to directive
this.myMethod = function() {}; //IS callable from controller passed to directive
});发布于 2015-12-16 00:46:02
如果您的指令没有独立的作用域,并且不需要ngController,则可以通过scope调用父控制器。
angular.module('app', [])
.controller('controller', function($scope) {
$scope.greet = function() {
return 'hi'
};
})
.directive('testDirective', function() {
return {
restrict: 'E',
template: '<h1>{{ greet() }}</h1>'
};
});输出:
hiPlnkr:http://plnkr.co/edit/uGXC5i1GjphcZCPDytDG?p=preview
发布于 2015-12-16 00:37:10
该函数需要在指令的作用域中可用。因此,如果您的指令在控制器的作用域中,那么它是:
scope.fn();https://stackoverflow.com/questions/34294528
复制相似问题