首頁 >後端開發 >php教程 >javascript - angular中使用了broadcast和on,為什麼on裡面的程式碼不是每次都成功運行?

javascript - angular中使用了broadcast和on,為什麼on裡面的程式碼不是每次都成功運行?

WBOY
WBOY原創
2016-10-22 00:14:14904瀏覽

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

如題,on裡面的程式碼為什麼不會每載入一次頁面都運行一次?

回覆內容:

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

如題,on裡面的程式碼為什麼不會每載入一次頁面都運行一次?

主要原因是在app的run中broadcast其實是一個非同步操作,如果說data這個Controller在run中的請求成功並且broadcast之前創建,就會成功調用,否則它接收不到root廣播過來的信息

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn