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

时间:2015-02-09 21:32:03

标签: javascript angularjs 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
});

3 个答案:

答案 0 :(得分:1)

在调用指令时,无法将函数定义为返回值的属性。它需要在您返回之前定义:

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函数内部采用相同的方式。

答案 1 :(得分:0)

只是为了玩耍:)

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);
        }
    };
});

答案 2 :(得分:0)

或使用方法绑定“&amp;”:

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>