angularjs如何在directive里调用controller的function

请问如何在directive里面调用controller的function?代码如下:

    var app = angular.module('myApp',[]);

    app.controller('myCtrl',function($scope){
       $scope.test= function(){
        ...
        }
    }
    app.directive('myDir',
    function(){
        return {
            restrict:'EA',
            replace: true,
            template: '<input ng-click="test()"></input>',
            scope:{
                test: '&'
            },
            controller: [
                '$scope', function ($scope) {
                    $scope.accept = function () {
                  
                       $scope.test();                       

                    };
                }
                ],
        }
    }
);

html是这样的:<button type="button" ng-click="accept()">test</button>

要怎样才能实现点击test button的时候在调用了directive里的accept function之后同时调用controller里面的test function呢?

阅读 4.5k
5 个回答
    var app = angular.module('myApp',[]);

    app.controller('myCtrl',function($scope){
       $scope.accept= function(){
        ...
        }
    }
    app.directive('myDir',
    function(){
        return {
            restrict:'EA',
            replace: true,
            template: '<input ng-click="test()"></input>',
            scope:{
                test: '&'
            },
            link: function(scope, element, attrs) {
                元素.bind("click",function(){
                    scope.accept();
                })
            }
        }
    }
);

你看看可不可以这样子弄

可以把myCtrl里的test function 存到service里,然后在directive里调用service里的test function

app.controller('myCtrl',function($scope,methods){
   $scope.test= function(){
    ...
    }
   methods.test = $scope.test;
}
app.factory('methods',function(){
        return {
            test: null
        };
})

app.directive('myDir',
    function(){
        return {
            restrict:'EA',
            replace: true,
            template: '<input ng-click="accept()"></input>',
            scope:{
                
            },
            controller: function ($scope,methods) {
                    $scope.accept = function () {
                       console.log('accept fn');
                       methods.test();
                    };
                }
        }
    }
);

或者:

var app = angular.module('myApp',[]);

app.controller('myCtrl',function($scope){
   $scope.test= function(){
    ...
    }
}
app.directive('myDir',function(){
    return {
        restrict:'EA',
        replace: true,
        template: '<input ng-click="test()"></input>',
        scope:{
            test: '&'
        },
        controller: function(){}
    }
});

HTML:
<my-dir test="test()"></my-dir>

<button type="button" ng-click="accept()">test</button> 这是 html 里的调用方式?
然后这个是 directie 的 template: <input ng-click="test()"></input>

所以你的 myDir 这个 directive 到底是在哪儿调用的?另外,如果方便,请你大概描述一下你要实现什么功能。

推荐问题
宣传栏