繁体   English   中英

Angularjs $在$ rootScope之后没有开火。$ broadcast

[英]Angularjs $on not firing after $rootScope.$broadcast

我有这个代码,其中两个控制器使用共享服务进行通信。

var app = angular.module('AdminApp', ['ngRoute']);

app.factory('SharedService', function ($rootScope) {

    var sharedService = {

        userId: [],

        BroadcastUserId: function (id) {
            this.userId.push(id);
            $rootScope.$broadcast('handleBroadcast');
        }
    };
    return sharedService;
});

app.config(function ($routeProvider) {

    $routeProvider.when('/login', {
        templateUrl: "adminLogin.html"
    });

    $routeProvider.when('/main', {
        templateUrl: 'adminMain.html'
    });

    $routeProvider.otherwise({
        redirectTo: '/login'
    });
});

app.controller('authCtrl', function ($scope, $http, $location, SharedService) {

    $scope.Userid = '';
    $scope.authenticate = function (user, pass) {
        $http.post('http://localhost/NancyAPI/auth', {
            UserName: user,
            Password: pass
        }).success(function (data) {
            $scope.$broadcast('Token', data.Token);
            $http.defaults.headers.common['Authorization'] = 'Token ' + data.Token;
            $scope.Userid = data.UserId;
            SharedService.BroadcastUserId($scope.Userid);
            $location.path("/main");
        }).error(function (response) {
            $scope.authenticationError = response.error || response;
        });
    };

    $scope.$on('handleBroadcast', function () {
        console.log('on');
    });
}).$inject = ['$scope', '$rootScope', 'SharedService'];

app.controller('mainCtrl', function ($scope, $http, $q, SharedService) {

    $scope.tests = [];
    $scope.userId = -1;

    $scope.getTests = function () {
        var deferred = $q.defer();
        $http.get('http://localhost/NancyAPI/auth/tests/' + $scope.userId).
            success(function (data) {
                deferred.resolve(data);
                $scope.tests = angular.fromJson(data);
            }).error(function (response) {
            });
    };

    // THIS IS NOT FIRING
    $scope.$on('handleBroadcast', function () {
        $scope.userId = SharedService.userId;
    });
}).$inject = ['$scope', '$rootScope', 'SharedService'];

由于某种原因, $scope.$onAuthCtrl控制器中触发,但不在mainCtrl

// THIS IS NOT FIRING
        $scope.$on('handleBroadcast', function () {
            $scope.userId = SharedService.userId;
        });

为什么会发生这种情况,我该如何解决?

我犯了一个微妙的错误,就是不提供{$ rootScope}作为依赖。 一旦我纠正了它,它对我有用。 我使用内联数组注释机制来实现相同的功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM