angularjs – 在指令控制器中访问需要控制器
发布时间:2020-12-17 17:24:54 所属栏目:安全 来源:网络整理
导读: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)
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() } }; }); 我不想使用链接方法,而是使用控制器方法. 就像是: 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; } }; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |