<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廣播過來的信息