请记住,使用 $broadcast、$rootScope、$apply...(以及其他一些)在 AngularJS 中确实是不好的做法
这是一个关于如何在控制器之间共享值的干净解决方案:(在此工作plunker http://plnkr.co/edit/HfzoFN0QsMTtxcSb10gl?p=preview)
Routing
$urlRouterProvider.when("","/mainpage");
$stateProvider
.state('app', {
abstract: true,
templateUrl: "main.template.html",
controller: "MainCtrl"
}).state('app.mainpage', {
url: "/mainpage",
templateUrl: "mainView.html",
controller:"PageCtrl"
});
控制器中的绑定
angular.module('MyApp').controller('MainCtrl', function($scope, UserService){
$scope.user = UserService.user;
});
angular.module('MyApp').controller('PageCtrl', function($scope, UserService){
$scope.user = UserService.user;
});
Service
angular.module('MyApp').service('UserService', function(){
var service = {};
service.user = {};
service.user.name = "Not connected";
return service;
});
带标题的模板
<p>I'm the header welcome {{user.name}}</p>
<hr/>
<ui-view></ui-view>
最终视图
<p>I'm the view : User : {{user.name}}</p>
<input type="text" ng-model="user.name">
<button ng-click="user.name='Derp'">Change name to Derp</button>
我不介意你投票,选择这个作为答案或最终使用它。我只是希望您记住有关在控制器之间共享值的常见问题的最佳实践。
希望有帮助。