问题描述
我一直在和Angular一起玩,我已经从使用本地数据(看起来工作正常)转到尝试从我工厂的ajax调用填充我的视图。
I've been playing with Angular and I've moved from working with local data (which seems to work fine) to trying to populate my view from an ajax call in my factory.
以下是代码:
<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数据,但是返回家庭没有没有数据到$ scope.family
Everything seems okay, I can see the json data in my console log, but "return family" doesn't get the data to $scope.family
我缺少什么?我知道它必须简单。
What am I missing? I know it has to be something simple.
谢谢!
推荐答案
要将数据处理完全抽象到工厂中,您可以从 $ http
返回承诺,并将返回保留在 .then()
:
To completely abstract the data handling into the factory, you can both return the promise from $http
and leave the return inside the .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;
});
这可确保调用工厂方法的控制器在准备就绪时获取数据。您还可以在工厂内而不是在控制器中处理错误检查等,从而完全分离问题。
This ensures the controller calling the factory method will get the data when it's ready. You can also handle error checking, etc, inside the factory and not in the controller, completely separating concerns.
这篇关于Angular:从工厂ajax调用将数据传回我的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!