如何在 Angular 指令中调用我自己的函数?

How to call my own function inside an Angular Directive?

我想在我的 angular 指令中调用 "myFunc()",我该怎么做?

myApp.directive("test", function () {
 return {
   restrict: 'A',
     template: "<div class='box'></div>",
     myFunc: function() {
                console.log('myFunc');
       },
     link: function ($scope, element, attrs) {

         element.bind('click', function () {
               myFunc(); //<------------- doesn't work
       });
     }
    } // of return
});

您不能在指令调用中将函数定义为 return 值的 属性。它要么需要在 return:

之前定义
myApp.directive('test', function() {
    var myFunc = function() {
        console.log('myFunc');
    };

    return {
        restrict: 'A',
        template: '<div class="box"></div>',
        link: function($scope, element, attrs) {
            element.bind('click', myFunc);
        }
    };
};

或者在您的 link 函数中使用相同的方法。

随便玩玩:)

var app = angular.module('myApp', []);
app.controller('MainController',function() {

});
app.directive('one', function() {
    return angular.extend({}, app.directive, {myfunct:function(){
                alert('hello');
    }});
});
app.directive('two', function(oneDirective) {
    return {
        link:function($scope,$element){
            console.log(oneDirective[0].myfunct)
            $element.on('click',oneDirective[0].myfunct);
        }
    };
});

或使用方法绑定"&":

app.directive('myDir', function() {
    return {
        scope: {
            callback: "&"  
        },
        link:function($scope,$element){

             element.bind('click', function () {
               $scope.evalAsync(function() {
                  $scope.callback({param1: value, param2: value2});
               })
             });
        }
    };
});

用法:

<my-dir callback="myControllerMethod(param1, param2)"></my-dir>