簡體   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