加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:27:48 所属栏目:安全 来源:网络整理
导读:我有这个代码: JS: angular.module("module") .controller("fooController",["$scope",function($scope) { ... }) .directive("foo",function() { return { restrict: "E",controller: "fooController",link: function($scope,$element,$attrs) { // Do so
我有这个代码:

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()函数与每个控制器进行通信.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读