Home >Backend Development >PHP Tutorial >javascript - Broadcast and on are used in angular. Why does the code in on not run successfully every time?

javascript - Broadcast and on are used in angular. Why does the code in on not run successfully every time?

WBOY
WBOYOriginal
2016-10-22 00:14:14913browse

<code>var app = angular.module('gzmu', ["ngRoute",'chart.js']);
app.run(function ($rootScope, $http) {

    $http({
        method: 'GET',
        url: 'datacon/user_info.php',

    }).success(function (response) {



            $rootScope.userinfo = response[0];
        console.log($rootScope.userinfo)
        $rootScope.$broadcast("userinfo", response[0]);



    })
});
app.controller('data', function ($scope, $http, $rootScope) {
    $scope.usernamea='';
    $scope.$on("userinfo",
        function (event, msg) {
            console.log(msg);
            if(msg){
                $scope.usernamea = msg.user;
                console.log($scope.usernamea)
                alert($scope.usernamea)
            }
            else{
                alert(msg)
            }

        });
});</code>

Like the title, why doesn’t the code in on run every time the page is loaded?

Reply content:

<code>var app = angular.module('gzmu', ["ngRoute",'chart.js']);
app.run(function ($rootScope, $http) {

    $http({
        method: 'GET',
        url: 'datacon/user_info.php',

    }).success(function (response) {



            $rootScope.userinfo = response[0];
        console.log($rootScope.userinfo)
        $rootScope.$broadcast("userinfo", response[0]);



    })
});
app.controller('data', function ($scope, $http, $rootScope) {
    $scope.usernamea='';
    $scope.$on("userinfo",
        function (event, msg) {
            console.log(msg);
            if(msg){
                $scope.usernamea = msg.user;
                console.log($scope.usernamea)
                alert($scope.usernamea)
            }
            else{
                alert(msg)
            }

        });
});</code>

Like the title, why doesn’t the code in on run every time the page is loaded?

The main reason is that broadcasting is actually an asynchronous operation in the run of the app. If the request of the data Controller in the run is successful and it is created before broadcast, it will be called successfully, otherwise it will not receive the information broadcast by the root

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn