2015-02-09 78 views
1

我想在我的角度指令中调用“myFunc()”,我该怎么做?如何在Angular指令中调用我自己的函数?

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

AFAIK这是不可能的,我认为你应该使用范围:'&'并将该功能放在控制器中,但可能您只是知道:) – Whisher 2015-02-09 21:43:59

回答

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函数内以同样的方式。

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

,或者使用方法绑定 “&”:

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> 
相关问题