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

前端之家收集整理的这篇文章主要介绍了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",require: "fooController",$attrs) {
         // Nothing yet
      }
    }
  });

HTML:

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

指令foo有效,但指令栏抛出错误:无控制器:fooController.

如何在保持当前结构的同时解决这个问题(Controller不在HTML中,但是指令使用,bar在foo之外并共享同一个控制器,而两者都在修改其范围)?我读了here的讨论,但我无法理解如何做到这一点.

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

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

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

然后,您可以在控制器中使用此服务,并使用服务的setData()和getData()函数与每个控制器进行通信.

原文链接:https://www.f2er.com/angularjs/142063.html

猜你在找的Angularjs相关文章