我有这个代码:
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.jb51.cc/angularjs/142063.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。