所有
现在,我在main.js中定义了一个基本模块和控制器:
main.js
var app = angular.module("test", []);
app.controller("main", ["$scope", function($scope){
$scope.data = [];
}]);
我在另一个sub.js中引用该模块:
sub.js
//From some tutorial I learned that remove the [] in module can refer to that module rather than re-defined it
var app = angular.module("test");
// Here comes my question, how to refer to that main controller?
我想定义一些可能与主控制器范围内的sub.js相关的内容,我想知道如何引用它并将变量添加到其范围内。
由于
答案 0 :(得分:1)
服务用于在控制器之间共享数据。它们是单例,并且比其他方式使控制器间通信复杂化更容易。
你不应该两次定义控制器(这不仅是一种不好的做法,而且还不会起作用)。
因此,使用该服务从主控制器保存您需要的内容,然后从子主页访问它。
更新
参见我所做的这个简单示例,Sub控制器正在访问从主控制器设置的值:
angular.module('app', [])
.controller('Main', function(myService){
myService.setData('some data from Main ctrl');
})
.controller('Sub', function(myService, $scope){
$scope.data = myService.getData();
})
.service('myService', function(){
var data;
return {
setData: function(d){
data = d;
},
getData: function(){
return data;
}
}
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="Main"></div>
<div ng-controller="Sub">
{{data}}
</div>
</body>
&#13;