angularjs – 在指令控制器中访问需要控制器

前端之家收集整理的这篇文章主要介绍了angularjs – 在指令控制器中访问需要控制器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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;
        }
    };
});

猜你在找的Angularjs相关文章