4

I'm attempting to update the main nav bar with the user's name, and also update the shopping cart icon with how many items he's bought. I haven't tried using $broadcast and $on before.

On successful post of a log in I set up a simple broadcast, this is in its own login controller:

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

Now I have the $on event in the controller where the shopping cart icon resides, but the value is never updated upon log in. In fact, I don't even get the console message, so it just never gets to 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 helpful, because there is lots more I keep to update on the main view when data in other views change. If it makes a difference I'm using UI-Router.

5
  • I will never recommend to use a $broadcast for sharing data accros the controllers. You should use a service instead Commented Jun 5, 2015 at 15:21
  • The console shows no errors, and no console.log that I broadcast. I do use several services throughout the website to share data, but could you explain why use it for this simple event I want fired? I suppose I might just go that route if nothing else works. Commented Jun 5, 2015 at 15:28
  • @mitbanip Sharing data is a common usecase in angular. Maintaining value in a single service is a best practice instead of maintaining this value in multiple place. I'm building a clean example with ui-router on a plunker Commented Jun 5, 2015 at 15:33
  • I'm using a factory to maintain Session variables. My only concern with broadcasting was the ability to send an event from one controller to another so I can update the view. If there's a better way I'd love to know it. But it just seems like it's the reason $broadcast is there? Commented Jun 5, 2015 at 15:45
  • As far as i know $broadcast is more technically used in directives. Its use in controllers is not really necessary. I'd admit that if you really send events you could use it. But actually all the events are already wrapped in angular directives (ng-click, ng-enter etc...) and if it's just a matter of updating var from one controller to another, i would definitly go with the service shared variable. Commented Jun 5, 2015 at 15:49

2 Answers 2

5

Keep in mind that the use of $broadcast, $rootScope, $apply... (and some others) are really bad practices in angularJS

Here is a clean solution on how to share a value between 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"
    });

Binding 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;

});

Template with the header

<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 don't mind you upvote, select this as the answer or finally use it. I just want you to keep in mind the best practice around this common problem about sharing values between controllers.

Hope it helped.

Sign up to request clarification or add additional context in comments.

1 Comment

It helped a lot and cleared things up for me. More importantly, it's clean and looks like good practice.
0

You're broadcasting to $rootScope so $rootScope.$on(...

1 Comment

This did get me a console.log broadcasted finally :) Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.