Rumah >pembangunan bahagian belakang >tutorial php >javascript - angular中使用了broadcast和on,为什么on里面的代码不是每次都成功运行?

javascript - angular中使用了broadcast和on,为什么on里面的代码不是每次都成功运行?

WBOY
WBOYasal
2016-10-22 00:14:14913semak imbas

<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广播过来的信息

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn