如何使用控制器两项指令? [英] How to use a controller for two directives?

查看:122
本文介绍了如何使用控制器两项指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code:

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>

指令的作品,但指令抛出一个错误:无控制器:FooController的

Directive foo works, but directive bar throws an error: No controller: fooController.

我怎样才能解决这个问题,同时保持我目前的结构(控制器不是HTML里面,但所使用的指令,之外并共享相同的控制器,而两者都修改它的范围)?我这里阅读讨论,但我不知道如何做到这一点。

How can I fix this while maintaining my current structure (Controller isn't inside the HTML, but is used by the directives, bar is outside foo and share the same controller, while both are modifying its scope)? I read the discussion here, but I couldn't understand how to do it.

推荐答案

由于您的最终目标是控制器之间的通信,你不必再使用多个指令相同的控制器(我怀疑,如果再使用将允许你通信)。总之,去它的最好方法是使用服务。

Since your ultimate objective is to communicate between controllers, you need not re-use the same controller across multiple directives (I doubt if re-using would allow you to communicate). Anyway, the best way to go about it would be use services.

一个控制器调用另一个AngularJS?谈它的细节,但简单来说,首先创建一个服务:

Article Can one controller call another in AngularJS? speaks about it in detail, but in simple terms, first create a service:

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

您就可以在控制器中使用此服务,并使用使用setData()的getData()功能。

You can then use this service in your controllers and communicate with each controller by using setData() and getData() functions of the service.

这篇关于如何使用控制器两项指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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