需要帮助来理解角度js中的异步调用

时间:2016-07-19 12:55:08

标签: angularjs

我有一个主控制器和嵌套控制器。在主控制器中,我通过对服务的异步查询定义了对象,并尝试在嵌套控制器中使用该对象。但是在嵌套控制器中的对象是空的,导致它在主控制器中更新之前触发。

据我所知,异步查询应该在数据获取后更新范围?

.controller('MainController', ['$scope', function($scope) {

    $scope.uData = {};
    $scope.uDataCurrent = {};

    $scope.usersData = usersFactory.getUsersData().query(
        function(response) {
            $scope.uData = response;
            $scope.uDataCurrent = $filter('filter')($scope.uData, {'user':$scope.myuser});
            $scope.uDataCurrent = $scope.uDataCurrent[0];
        },
        function(response) {
            $scope.message = "Error: "+response.status + " " + response.statusText;
    });
})]

.controller('NestedController', ['$scope', function($scope) {
    console.log($scope.uDataCurrent); // returns empty object
}])

服务:

    .service('usersFactory', ['$resource', 'baseURL', function($resource,baseURL) {

        this.getUsersData = function(){
            return $resource(baseURL+"/index.php?app=users&format=raw&resource=user",null,  {'update':{method:'PUT' }});
        };

    }])

1 个答案:

答案 0 :(得分:0)

您可以使用$scope.$watch

angular.module("App", [])
.controller("OuterCtrl", ["$scope", "$timeout", function($scope, $timeout) {
  $scope.users = null;
  
  $timeout(function() {
    $scope.users = ["John", "Jack"];
  }, 500);
}]).controller("InnerCtrl", ["$scope", function($scope) {
  
  $scope.changeCount = 0;
  
  // TODO: Bad practice to rely on outer scopes here as its not enforced
  // to have an OuterCtrl scope as parent scope. In this example every
  // occurrences of InnerCtrl is embedded in an OuterCtrl in the html
  $scope.$watch("users", function(newValue, oldValue) {
    // This code runs when the users array is changed
    $scope.changeCount++;
  });
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.js"></script>

<div ng-app="App">
  <div ng-controller="OuterCtrl">
    <div ng-controller="InnerCtrl">
      <div>Change count: {{changeCount}}</div>
      <div>Users</div>
      <div ng-hide="users"> Loading...</div>
      <ul>
        <li ng-repeat="name in users">{{name}}</li>
      </ul>
    </div>
  </div>
</div>