我创建了countryApp模块。我在aboutCtrl中创建了“names”数组。
我想在insertContact函数中访问contactCtrl中的“names”数组。
{{1}}
答案 0 :(得分:0)
扩展Claies'实际代码的解决方案:
countryApp.controller('aboutCtrl', function($scope, dataService) {
/* If you're binding the values into your HTML,
you need to $watch the service variable 'names' */
$scope.$watch(function() { return dataService.names }, function() {
$scope.names = dataService.names;
});
dataService.names = [{name:'venu',number:'22222',sex:'male'},{name:'Aishu',number:'1111',sex:'female'},{name:'Milky',number:'2222',sex:'female'}]
});
countryApp.controller('contactCtrl', function($scope, dataService) {
/* You can place the same watch as in aboutCtrl here if
you're displaying stuff in HTML that's related to this controller */
$scope.greeting = 'Hello, World!';
$scope.insertContact = function () {
alert(dataService.names);
}
$scope.resetContact = function () {
}
});
countryApp.service('dataService', function() {
var dataObj = {};
dataobj.names = [];
return dataObj;
});
请注意有关$watch
服务变量的评论;如果您想通过$scope
变量在视图中显示值,则需要$watch
相应的服务变量或$scope
变量不会更新当服务变量的值改变时。
答案 1 :(得分:0)
如果您想在两个控制器之间进行通信,请参考以下小提琴:
Fiddle
:http://jsfiddle.net/VaibhavP17/nky45/
它显示了如何在两个控制器之间进行通信以及事件的细微差别。我希望这会有所帮助:)