如何将控制器用于两个指令?

时间:2013-06-05 08:29:14

标签: angularjs

我有这段代码:

JS:

angular.module("module")
  .controller("fooController", ["$scope", function($scope) {
    ...
  })
  .directive("foo", function() {
    return {
      restrict: "E",
      controller: "fooController",
      link: function($scope, $element, $attrs) {
        // Do some things with the scope of the controller here
      }
    }
  })
  .directive("bar", function() {
    return {
      restrict: "E",
      require: "fooController",
      link: function($scope, $element, $attrs) {
         // Nothing yet
      }
    }
  });

HTML:

<html>
  <head>
    <!-- Scripts here -->
  </head>
  <body ng-app="module">
    <foo/>
    <bar/>
  </body>
</html>

指令foo有效,但指令bar会引发错误:No controller: fooController

如何在保持当前结构的同时修复此问题(控制器不在HTML内部,但由指令使用,barfoo之外并共享同一个控制器,而两者都是修改其范围)?我阅读了讨论here,但我不明白该怎么做。

2 个答案:

答案 0 :(得分:5)

由于您的最终目标是在控制器之间进行通信,因此您无需在多个指令中重复使用相同的控制器(我怀疑重新使用是否允许您进行通信)。无论如何,最好的方法是使用服务。

文章Can one controller call another?详细说明了这一点,但简单来说,首先要创建一个服务:

app.factory('myService', function () {
    var data;
    return {
        getData: function () {
            return data
        },
        setData: function (newData) {
            data = newData;
        }
    };
});

然后,您可以在控制器中使用此服务,并使用该服务的setData()getData()功能与每个控制器进行通信。

答案 1 :(得分:4)

您不能要求控制器。您可以要求一个指令,该指令是当前指令的父节点之一。

   <foo>
      <bar />
   </foo>

   // in foo
   controller: 'fooController'
   // in bar
   require: '^foo' // ^ means to search it up in the tree

这里bar可以要求foo,它将拥有foo的控制器:http://jsfiddle.net/Zmetser/kHdVX/ 在这个例子中,fooController将被初始化一次。

   <foo />
   <bar />

   // in foo
   controller: 'fooController'
   // in bar
   controller: 'fooController'

这里bar和foo有fooController的实例:http://jsfiddle.net/Zmetser/QypXn/

相关问题