【问题标题】:Angular directive to directive communication?角度指令到指令通信?
【发布时间】:2014-08-15 22:38:53
【问题描述】:

实际上,我只需要在某个地方放置一个可以访问 $scope 的可重用函数。

这是我正在尝试做的一个简化示例的尝试:Plnkr

我仍然掌握指令的窍门。

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

app.directive('dir1', function() {
    return {
        restrict: 'AE',
        link: function(scope, element, attrs) {
            element.click(function() {
                scope.message = "Hey Now";
                scope.doSomething();
            });
        }
    };
});

app.directive('dir2', function() {
    return {
        restrict: 'AE',
        link: function(scope, elem, attr) {
            scope.doSomething = function() {
                alert($scope.message);
            }
        }
    };
});

和:

<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body>
  <dir1>click me</dir1>
</body>
</html>

【问题讨论】:

  • 你永远不会在任何地方使用 dir2。你到底想达到什么目的?
  • 我只想要一个可重用的函数来改变 DOM 并可以访问 $scope @JBNizet
  • 可以被什么重用?如果只有一个指令 dir1 使用它,请将其放在 dir1 指令中。如果它实际上被几个人使用,请将其放在以范围为参数的服务中。
  • 服务会很棒,但它也必须编译 html: $compile(canvas)($scope); $scope.$apply();我需要做的不仅仅是向它传递参数。 @JBNizet

标签: angularjs


【解决方案1】:

您可以使用指令的require 参数来与另一个指令通信。这是一个例子:

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

app.directive('dir1', function(){
return {
  restrict: 'AE',
  require:'dir2',
  link: function(scope, element, attrs, dir2) {

         element.bind('click', function() {

           dir2.message = "Hey Now";
           alert(JSON.stringify(dir2))
           dir2.doSomething();

         });

  }
};
});

app.directive('dir2', function(){
return {
  restrict: 'AE',
  controller : function ($scope) {
     this.doSomething = function(){
       alert(this.message);
     }

  }

};
});

【讨论】:

  • 问题在于没有名为 'dir2' 的 html 元素,它给出了错误:“$compile:ctreq Missing Required Controller - Controller 'dir2', required by directive 'dir1', can't被发现!”并添加“^?”到 'require' 参数会导致它无法识别 'dir1' 函数。
  • @jthomasbailey 你真的需要两个不同的指令吗?似乎您可以处理一个并使用另一个只是从父范围传递参数
  • 我也许可以将第二个指令分割成一个服务和几个函数,我可以把它们放在一个可以访问 $scope 的控制器中,不过我并不期待它。我不敢相信 Angular 会因为这么简单的事情给我带来这么多麻烦。
猜你喜欢
  • 2016-05-05
  • 2017-04-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
相关资源
最近更新 更多