因为我有很多 Controller 或多或少执行相同的操作,所以我想创建一个函数来获取 XML 文件的文件名并将其分配给 $scope
变量。明显的问题是异步调用。
是否有“暂停”或其他情况会阻止 ngXMLFile
函数结束,直到 AJAX 调用完成,以便它不会将 undefined
分配给 $scope.authors
因为 sectionController
中的 data
是 未定义
?
我尝试了这个$.when
,但很明显我没有正确使用它。
function ngXMLFile($http, filename) {
$http({method: "GET", url: "/xml/"+filename+".xml"}).
success(function(data, status, headers, config) {
return $.xml2json(data);
}).
error(function(data, status, headers, config) {
});
}
function sectionController($scope, $http) {
$.when(ngXMLFile($http, "authors")).then(function(data) {
$scope.authors = data;
});
}
XML 文件(authors.xml):
<?xml version="1.0" encoding="UTF-8"?>
<authors>
<author>
<name>
<first>Bob</first>
<last>Smith</last>
</name>
</author>
<author>
<name>
<first>Joe</first>
<last>King</last>
</name>
</author>
</authors>
最佳答案
您想要的是将回调函数传递给您的 Ajax 调用函数,例如:
function ngXMLFile($http, filename, callback) {
$http({method: "GET", url: "/xml/"+filename+".xml"}).
success(function(data, status, headers, config)
{
callback($.xml2json(data));
}
).
error(function(data, status, headers, config)
{
}
);
}
function sectionController($scope, $http) {
ngXMLFile($http, "authors",function(data) {
$scope.authors = data;
});
}
关于javascript - AJAX XML数据到$scope,同步性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336010/