从指令调用控制器方法而不在指令元素上定义它 - AngularJS

jwe*_*est 1 angularjs

我敢肯定有一个简单的答案,我错过了.

http://jsfiddle.net/jonathanwest/pDRxw/3/

本质上,我的指令将包含控件,这些控件总是在指令本身外部的控制器中调用相同的方法.正如你从上面的小提琴中看到的那样,我可以通过在control指令上使用方法定义属性来完成这项工作,但是因为该方法将始终从指令中的相同按钮调用,所以我不想要定义要打电话的方法.相反,指令应该知道在edit按下该按钮时调用控制器方法.因此,定义control将是:

<control title="Custom Title" />

我怎样才能做到这一点?

Val*_*nov 5

实际上我认为直接使用$parent它并不是一种推荐的方式应该如何定义指令.因为实际上没有可见的依赖关系可以从父控制器调用哪些函数,使它们更难以重复使用.

我不知道实际用例为什么你需要这个,但我假设你使用control了几次而且你不想复制粘贴定义一些常见行为的一堆属性.

在这种情况下,我会推荐一些其他方法:添加一些定义该行为的指令容器,控件将需要此指令作为依赖:

myApp.directive('controlBehavior', function() {
    return {
        restrict: 'E',
        scope: {
            modifyfunc: '&'
        },        
        controller: function($scope, $timeout) {
            this.modifyfunc = $scope.modifyfunc;
        }
    };
});
myApp.directive('control', function() {
    return {
        restrict: 'E',
        require: '^controlBehavior',
        replace: true,
        scope: {
            title: "@"
        },
        template : '<div>{{title}}<button ng-click="edit()">Edit</button></div>',
        link: function(scope, element, attr, behavior) {            
            scope.edit = behavior.modifyfunc;   
        }            
    }
});
Run Code Online (Sandbox Code Playgroud)

这是演示这种方法的小提琴:http://jsfiddle.net/7EvpZ/4/