【问题标题】:angular broadcast not updating on second call角度广播未在第二次通话时更新
【发布时间】:2015-11-21 19:18:27
【问题描述】:

我有一个调用服务的控制器。在服务中,我执行了一个 $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 控制器。

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

但是,单击带有ng-click="Next()" 的按钮时,尽管再次调用该服务,{{myValue}} 仍显示为 1,而不是 1 + 1 = 2。

有什么想法吗?

【问题讨论】:

  • 你能创建一个plunker吗?

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


【解决方案1】:

你没有用计数器计数。 尝试使用++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);
    };
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 2021-11-27
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 2012-08-17
    • 2015-09-01
    • 1970-01-01
    相关资源
    最近更新 更多