初始化控制器通过Ajax请求初始化、控制器、Ajax

2023-09-10 20:42:14 作者:梅巛內酷

我有AngularJs控制器:

I have the AngularJs controller:

function MyController($scope, $http) {
   // as $http.get() is async, success() returns promise but 
   // I need the actual value 'items'
   var promise = $http.get(...)
       .success(function(response) {return response.items;});
   <waitForAjaxCall>
   $scope.items = promise.get?();
   $scope.firstItem = $scope.items[0];

   //do stuff using $scope.firstItem
}

var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', '$http', MyController]);

我如何确保 $ scope.items 是由之前的 $ scope.firstItem =由Ajax调用返回的值初始化.. 分配?另一种方法我看到的是在angularjs工厂调用$ HTTP包项目,但我仍然需要等待AJAX​​调用来完成这个工厂里面。

How can I ensure that $scope.items is initialized by a value returned by the ajax call before the $scope.firstItem = ... assignment? Another approach I see is to wrap items in angularjs factory that calls $http, but I still need to wait for the ajax call to complete inside this factory.

推荐答案

您不能等待同步的Ajax调用来完成。你需要初始化成功之内的范围回调:

You can't wait synchronously for the Ajax call to complete. You need to initialize the scope within the success callback:

function MyController($scope, $http) {
    function init(items) {
        $scope.items = items;
        $scope.firstItem = $scope.items[0];

        //do stuff using $scope.firstItem
    }

    $http.get(...)
        .success(function(data) {
            init(data.items);               
        });
}