AngularJS $ Broadcast and $ on without updating $ scope

I am trying to update the main navigation bar with the username, as well as update the shopping cart icon, how many things he bought. I have not tried using $ broadcast and $ before.

In a successful log entry, I installed a simple translation, this is in my own login controller:

$rootScope.$broadcast('user-logged-in');

Now I have a $ on event in the controller where the shopping cart icon is located, but the value is never updated when I log in. In fact, I don’t even get a console message, so it just doesn’t reach it,

$scope.$on('user-logged-in', function  (event, args) {
            console.log("Broadcasted to Products Controller");
            $scope.logged= Session.isLogged();
            $scope.username= Session.recallName();
        });

Learning how to use this would be very useful, because there are many more that I want to update on the main view when the data in other views changes. If that matters, I use a UI-Router.

+4
source share
2 answers

You broadcast on $rootScope, therefore$rootScope.$on(...

0
source

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.

+5
source

All Articles