How to call a method defined in an AngularJS directive?

前端 未结 13 1316
萌比男神i
萌比男神i 2020-11-22 14:39

I have a directive, here is the code :

.directive(\'map\', function() {
    return {
        restrict: \'E\',
        replace: true,
        template: \'<         


        
13条回答
  •  猫巷女王i
    2020-11-22 15:14

    Assuming that the action button uses the same controller $scope as the directive, just define function updateMap on $scope inside the link function. Your controller can then call that function when the action button is clicked.

    app.directive('map', function() {
        return {
            restrict: 'E',
            replace: true,
            template: '
    ', link: function($scope, element, attrs) { $scope.updateMap = function() { alert('inside updateMap()'); } } } });

    fiddle


    As per @FlorianF's comment, if the directive uses an isolated scope, things are more complicated. Here's one way to make it work: add a set-fn attribute to the map directive which will register the directive function with the controller:

    
    
    
    scope: { setFn: '&' },
    link: function(scope, element, attrs) {
        scope.updateMap = function() {
           alert('inside updateMap()');
        }
        scope.setFn({theDirFn: scope.updateMap});
    }
    
    function MyCtrl($scope) {
        $scope.setDirectiveFn = function(directiveFn) {
            $scope.directiveFn = directiveFn;
        };
    }
    

    fiddle

提交回复
热议问题