初始化控制器通过Ajax请求 [英] Initialize controller by ajax request
本文介绍了初始化控制器通过Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有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);
});
}
这篇关于初始化控制器通过Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文