AngularJS: How do I call a function defined in a directive's scope from a controller?

*爱你&永不变心* 提交于 2019-12-08 17:47:23

You can call a controller function inside the link block. You can also $emit an event in the directive and listen to the it in the controller (maybe there is a use case for that).

It seems that you want to call it on mouseenter. You can do that by binding to the mouseenter event in the directive link. The catch is you need to $apply the changes. Take a look at the following piece of code, which contains all 3 examples: http://jsbin.com/cuvugu/8/. (also pasted below)

Tip: You might want to pay attention to how you name your directives. To use a directive as my-directive you need to name it as myDirective.

var app = angular.module('App', []);

app.directive('myDirective', function () {
  function directiveLink(scope){
    scope.$emit('customEvent');
  }

  return {
    restrict: 'EA',
    scope: {},
    link: directiveLink,
    controller: function ($scope) {
      $scope.bar = 'bar';
      $scope.myFunction = function () {
        $scope.bar = 'foobar1';
      };

      $scope.$on('customEvent', function (){
        $scope.myFunction();
      });
    },
    template: "Foo {{bar}}"
  };
});

app.directive('anotherDirective', function () {
  function directiveLink(scope){
    scope.myFunction();
  }

  return {
    restrict: 'EA',
    scope: {},
    link: directiveLink,
    controller: function ($scope) {
      $scope.bar = 'bar';
      $scope.myFunction = function () {
        $scope.bar = 'foobar2';
      };
    },
    template: "Foo {{bar}}"
  };
});

app.directive('mouseDirective', function () {
  function directiveLink(scope, element){
    element.bind('mouseenter', function(){
      scope.$apply(function(){
        scope.myFunction();
      });
    });

    element.bind('mouseleave', function(){
      scope.$apply(function(){
        scope.myOtherFunction();
      });
    });
  }

  return {
    restrict: 'EA',
    link: directiveLink,
    controller: function ($scope) {
      $scope.bar = 'no';
      $scope.myFunction = function () {
        $scope.bar = 'yes';
      };

      $scope.myOtherFunction = function () {
        $scope.bar = 'no';
      };
    },
    template: "Mouse Enter: {{bar}}"
  };
});

I also included an example with a distinct controller in the JS Bin link. That doesn't really change anything, but it seems to be an important part of your question. Here's the code block:

var app = angular.module('App', []);

app.controller('myController', function($scope){
  $scope.bar = 'foo';

  $scope.myFunction = function(){
    $scope.bar = 'foobar3';
  };
});

app.directive('lastDirective', function () {
  function directiveLink(scope){
    scope.myFunction();
  }

  return {
    restrict: 'EA',
    scope: {},
    link: directiveLink,
    controller: 'myController',
    template: "Foo {{bar}}"
  };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!