我一直在使用 Angular,并且已经从使用本地数据(似乎工作正常)转向尝试通过工厂中的 ajax 调用来填充我的 View 。
代码如下:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
</head>
<body>
<div ng-app="testApp">
<h2>Get data using a Factory</h2>
<div ng-controller="simpleController">
<input type="text" placeholder="Filter" ng-model="name">
<ul>
<li ng-repeat="person in family | filter:name">[{{$index + 1}}] {{person.name}} - {{person.age}}</li>
</ul>
</div>
</div>
<script>
// our very, very simple controller - on the page itself
var testApp = angular.module('testApp', []);
testApp.factory('simpleFactory', function($http) {
var family = [
{name: 'Joe', age: 40},
{name: 'Maryellen', age: 37},
{name: 'Isaac', age: 12},
{name: 'Emilie-Alice', age: 14}
];
var factory = {};
factory.getFamily = function() {
return family;
}
factory.getFamily2 = function() {
$http.get('/family.json').then(function(result) {
family = result.data;
console.log(family); // I see the objects!
return family; // this doesn't return the data like getFamily() does - why???
});
}
return factory;
});
testApp.controller('simpleController', function($scope, simpleFactory) {
$scope.family = [];
init();
function init() {
$scope.family = simpleFactory.getFamily2();
}
});
</script>
</body>
</html>
一切看起来都不错,我可以在控制台日志中看到 json 数据,但是“return family”无法将数据获取到 $scope.family
我错过了什么?我知道它必须是简单的事情。
谢谢!
最佳答案
要将数据处理完全抽象到工厂中,您可以从 $http
返回 Promise,并将返回值保留在 .then()
中:
factory.getFamily2 = function() {
return $http.get('/family.json').then(function(result) {
family = result.data;
console.log(family); // I see the objects!
return family; // this doesn't return the data like getFamily() does - why???
});
}
function init() {
simpleFactory.getFamily2().then(function(data){
$scope.family = data;
});
这确保调用工厂方法的 Controller 将在数据准备好时获取数据。您还可以在工厂内部而不是在 Controller 中处理错误检查等,从而完全分离关注点。
关于javascript - Angular : Passing data back to my controller from a factory ajax call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151465/