app.directive('mainCtrl',function () { return { controller: function () { this.funcA = function(){} } }; }); app.directive('addProduct',function () { return { restrict: 'E',require: '^mainCtrl',link: function (scope,lElement,attrs,mainCtrl) { mainCtrl.funcA() } }; });
我不想使用链接方法,而是使用控制器方法.
有没有办法在指令addProduct的控制器方法中获取mainCtrl.
就像是:
app.directive('addProduct',controller: function (scope,mainCtrl) { mainCtrl.funcA() } }; });
解决方法
您仍然需要使用链接功能,因为控制器是在那里注入的.但是,您可以请求您的指令自己的控制器,然后将其他所需的控制器设置为其属性:
app.directive('addProduct',require: ['addProduct','^mainCtrl'],controller: function ($scope) { // this.mainCtrl is still not set here // this.mainCtrl.funcA(); // this will cause an error // but typically it is invoked in response to some event or function call $scope.doFuncA = function(){ this.mainCtrl.funcA(); } },link: function(scope,element,ctrls){ var me = ctrls[0],mainCtrl = ctrls[1]; me.mainCtrl = mainCtrl; } }; });