>  기사  >  백엔드 개발  >  javascript - 브로드캐스트와 on이 각도에서 사용됩니다. on의 코드가 매번 성공적으로 실행되지 않는 이유는 무엇입니까?

javascript - 브로드캐스트와 on이 각도에서 사용됩니다. on의 코드가 매번 성공적으로 실행되지 않는 이유는 무엇입니까?

WBOY
WBOY원래의
2016-10-22 00:14:14852검색

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

앞서 언급한 것처럼 페이지가 로드될 때마다 코드가 실행되지 않는 이유는 무엇입니까?

답글 내용:

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

앞서 언급한 것처럼 페이지가 로드될 때마다 코드가 실행되지 않는 이유는 무엇입니까?

주된 이유는 앱 실행 중 브로드캐스팅이 실제로 비동기 작업이기 때문입니다. 데이터 컨트롤러가 실행 중에 성공적으로 요청되고 브로드캐스트 전에 생성되면 성공적으로 호출되고, 그렇지 않으면 정보를 수신하지 못합니다. 루트로 방송

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.