我有這樣的代碼:如何使用兩個指令的控制器?
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
並共享相同的控制器,而兩者都修改它的範圍)?我閱讀here的討論,但我無法理解如何去做。
出於好奇,爲什麼你對這兩個指令使用相同的控制器? – callmekatootie
我需要在它們之間共享一些數據。你知道更好的方法來做到這一點嗎? – tgkokk
是 - 服務! '$ rootScope'也是這樣做的,但會被人詬病。 http://stackoverflow.com/questions/9293423/can-one-controller-call-another-in-angularjs - 這就是你需要知道的在控制器之間進行通信的全部內容。 – callmekatootie