Search code examples
javascriptangularjsangularjs-scopeangular-servicesangular-broadcast

angular broadcast not updating on second call


I have a controller which calls a service. Within the service, i perform a $rootScope.$broadcast which works perfectly on page load. However, when i call the service again, the $rootScope.$broadcast doesnt seem to be called.

Controller:

app.controller('MyController', function($scope, myService) {

    myService.inititate($scope);

    $scope.Next = function () {
        myService.next($scope);
    };    
});

Service:

app.service("loginService", function ($http, $rootScope) {

    var counter = 0;

    var checkuser = function (scope) {
        //some code.....
        $rootScope.$broadcast('rcvrCast', counter + 1);
    }

    this.inititate = function (scope) {
        //some code.....
        checkuser(scope);
    };

    this.next = function (scope) {
        //some code.....
        checkuser(scope);
    };
);

Directive:

app.directive('myDirective', function() {
    return {
        restrict: 'A',
        replace: true,
        scope: {},
        link: function(scope, element, attrs) {
            scope.$on("rcvrCast", function(event, val) {
                scope.myValue = val;
            });
        },
        template:
            '<section>' +
                '<p>{{myValue}}</p>' +                        
            '</section>'
    }
});

HTML:

<body ng-controller="ParentController">

    <section my-directive></section>

    <div ui-view></div>
</body>

The index.html page loads MyController controller.

On page load, the $broadcast called from this.inititate is successfully being called and {{myValue}} displays as 1.

However, on click on my button which has ng-click="Next()", although the service is being called again, {{myValue}} is still showing as 1, rather than 1 + 1 = 2.

Any thoughts?


Solution

  • You are not counting with the counter. Try using ++counter instead of counter+1

    app.service("loginService", function ($http, $rootScope) {
    
        var counter = 0;
    
        var checkuser = function (scope) {
            //some code.....
            $rootScope.$broadcast('rcvrCast', ++counter);
        }
    
        this.inititate = function (scope) {
            //some code.....
            checkuser(scope);
        };
    
        this.next = function (scope) {
            //some code.....
            checkuser(scope);
        };
    );