Keep in mind that using $ broadcast, $ rootScope, $ apply ... (and some others) are really bad practices in angularJS
Here is a clean solution on how to distribute the value between the controllers: (working in this plunker )
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"
});
Linking in controllers
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;
});
Header Template
<p>I'm the header welcome {{user.name}}</p>
<hr/>
<ui-view></ui-view>
Final 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>
I do not mind you, choose this as the answer or, finally, use it. I just want you to remember the best practice around this common problem of exchanging values between controllers.
Hope this helps.
source
share