角度广播在第二次呼叫时不更新

时间:2015-08-27 12:01:43

标签: javascript angularjs angularjs-scope angular-services angular-broadcast

我有一个调用服务的控制器。在服务中,我执行$ rootScope。$ broadcast,它在页面加载时完美运行。但是,当我再次调用该服务时,$ rootScope。$ broadcast似乎没有被调用。

控制器:

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

    myService.inititate($scope);

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

服务:

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);
    };
);

指令:

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>

index.html页面加载MyController控制器。

在页面加载时,$broadcast调用的this.inititate成功调用,{{myValue}}显示为1。

但是,点击我的ng-click="Next()"按钮,虽然再次调用该服务,{{myValue}}仍显示为1,而不是1 + 1 = 2.

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你不计算柜台。 尝试使用++counter代替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);
    };
);