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