我有这个代码:
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中,但由指令使用,bar在外部foo并共享同一个控制器,同时两者都在修改其范围)?我在这里阅读了讨论,但我无法理解如何去做.
由于您的最终目标是在控制器之间进行通信,因此您无需在多个指令中重复使用相同的控制器(我怀疑重新使用是否允许您进行通信).无论如何,最好的方法是使用服务.
文章一个控制器可以调用另一个 详细讲述它,但简单来说,首先要创建一个服务:
app.factory('myService', function () {
    var data;
    return {
        getData: function () {
            return data
        },
        setData: function (newData) {
            data = newData;
        }
    };
});
然后,您可以在控制器中使用此服务,并通过使用setData()和getData()服务功能与每个控制器进行通信.
| 归档时间: | 
 | 
| 查看次数: | 6566 次 | 
| 最近记录: |