Angular.js调用控制器中的指令函数

Angular.js call directive function in controller

本文关键字:指令 函数 控制器 js 调用 Angular      更新时间:2023-09-26

我想调用指令中定义的函数,与这个stackoverflow问题正好相反

我试过了,但不起作用。

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.someDirectiveFn = function(arg) {
                 return "in directive";
            };
        },
    }
});
function MyCtrl($scope) {
    alert($scope.someDirectiveFn());
}

这可能吗?我怎么能拿到它?这是一种不好的做法吗?

编辑

我是这样想的:

.controller('MyCtrl', function($scope) {
    alert($scope.func());
})
.directive('myDirective', function() {
    return {
      controller: function($scope, $element){
        $scope.func = function() {
          return "text";
         };
      }
    }
});

您可以使用事件系统来实现这一点。

首先,在具有参数的作用域上发出一个自定义事件。其次,使用angular$on方法倾听指令中的作用域。

app.controller('MyCtrl', function($scope) {
  $scope.invokeDirectiveMethod = function() {
    $scope.$emit('invokeMyDirectiveMethod', 'myParameter');
  };
})
.directive('myDirective', function() {
  return {
    link: function(scope, element, attrs) {
      var someDirectiveFn = function(event, arg) {
        alert(arg + " in directive");
      };
      scope.$on('invokeMyDirectiveMethod', someDirectiveFn);
    },
  }
});

这是一个正在工作的plunker。

更新

根据您的更新,事件通信不适合您的问题。

使用双向绑定将对象传递给指令并在该对象中定义someDirectiveFn如何?通过这种方式,您可以传递参数并从中返回值

app.controller('MyCtrl', function($scope) {
  $scope.shareObject = {};
  $scope.invokeDirectiveMethod = function() {
    if (angular.isFunction($scope.shareObject.someDirectiveFn)) {
      $scope.message = $scope.shareObject.someDirectiveFn('from controller'); 
    }
  };
})
.directive('myDirective', function() {
  return {
    scope: {
      'shareObject': '='
    },
    link: function(scope, element, attrs) {
      scope.shareObject.someDirectiveFn = function(arg) {
        return arg + ' from parameter';
      };
    },
  }
});

更新了plunker。

您没有发布html代码,所以我假设您的自定义指令在MyCtrl中使用。这是不起作用的,因为函数是在什么时候执行的。

控制器功能总是在链接功能之前执行。

这是一篇关于差异的很酷的文章。

因此,如果你想让你的控制器能够调用指令中的函数,你可以广播事件(比如halilb的答案),或者让指令监听特定的范围值,比如:

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.$watch("message", function() { console.log(message); });
        },
    }
});
function MyCtrl($scope) {
    $scope.message = "Hello Directive";
}

我猜你想要一个在指令和控制器之间共享的函数,比如说?

如果是这种情况,那么创建一个服务并将该服务注入directive和ctrl中如何。这样你只需要创建一次。

  app.service('sharedFucntionService', function() {
     return {
        someFn : function (arg) {
             alert(arg + " in directive")  
        }
    }
 });

将服务注入指令

 app.directive('myDirective',function( sharedFucntionService){
  return {
        link: function (scope, element, attrs) {
            // do something with sharedFucntionService
        }
    }

});

将服务也注入控制器函数MyCtrl($scope,sharedFuctionService){。。。。。。}