AngularJS:如何从控制器调用在指令范围内定义的函数? [英] AngularJS: How do I call a function defined in a directive's scope from a controller?

查看:22
本文介绍了AngularJS:如何从控制器调用在指令范围内定义的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用属于我的 Angular 应用程序中使用的 ng 指令的 $scope 的函数.

I need to call a function which belongs to the $scope of a ng-directive used in my Angular application.

假设指令是这样定义的:

Let's say the directive is defined like this:

.directive('my-directive', ['$document', '$timeout', function ($document, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            // ....
        },
        controller: ['$scope', function ($scope) {

            $scope.myFunction= function (mouseEnter) {
                // ...
            };
        }
    };
}]);

我需要从我的控制器(我们称之为 my-controller)调用 myFunction,它是放置我的指令的视图的控制器.

I need to call myFunction from my controller (let's call it my-controller) which is the controller of the view where my directive is placed.

能做到吗?(最终修改指令)

Is it possible to do it? (eventually modifying the directive)

EDIT :提供的已经回答的问题(建议编辑)与我的相似,因为我不清楚或者它显然没有解决我提出的具体问题.

EDIT : The already answered question provided (proposed for edit) is similar to mine by it's not clear to me or it doesn't apparently solve the specific problem I proposed.

EDIT 2:从 Dan M. 回答开始(不考虑 mouseenter/mouseleave.只是想让两个控制器相互通信),我通过以下方式将我的事件广播到指令的控制器$rootScope(因为两个控制器之间没有父子关系)通过:

EDIT 2: starting from Dan M. answer (without taking mouseenter/mouseleave in consideration. just trying to make the two controllers communicate with each other), I broadcasted my event to my directive's controller through $rootScope (as there is there is no parent-child relation between the two controllers) by:

console.log("let's broadcast the event.."); // this is printed
$rootScope.$broadcast('callDirectiveControllersFunction'); // I even tried with $scope in place of $rootScope and $emit in place of $broadcast

并通过以下方式接收它(在指令的控制器中):

and by receving it (within the directive's controller) by:

var myFunction = function(){
   // ...
}

$scope.$on('callDirectiveControllersFunction', function (){
   console.log("event received"); // this is not printed
   callMyFunction(); 
});
// I even tried using $rootScope in place of $scope

但是在没有任何情况(见代码注释)事件被接收

However in no case (see comments in code) the event is received

推荐答案

您可以在链接块内调用控制器函数.您还可以$emit 指令中的事件和在控制器中听它(也许有一个用例).

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).

看来你想在mouseenter上调用它.您可以通过绑定到指令链接中的 mouseenter 事件来实现.问题是您需要 $apply 更改.看看下面这段代码,其中包含所有 3 个示例:http://jsbin.com/cuvugu/8/.(也粘贴在下面)

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)

提示:您可能需要注意如何命名指令.要将指令用作 my-directive,您需要将其命名为 myDirective.

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

我还在 JS Bin 链接中包含了一个带有独特控制器的示例.这并没有真正改变任何东西,但它似乎是您问题的重要组成部分.这是代码块:

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

这篇关于AngularJS:如何从控制器调用在指令范围内定义的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆