我一直在玩Angular,我已经从使用本地数据(这似乎工作正常)转到尝试从我工厂的ajax调用填充我的视图。
以下是代码:
<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
我错过了什么?我知道它必须简单。
谢谢!
答案 0 :(得分:2)
要将数据处理完全抽象到工厂,您可以从$http
返回承诺,并将返回保留在.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;
});
这可确保调用工厂方法的控制器在准备好后获取数据。您还可以在工厂内而不是在控制器中处理错误检查等,从而完全分离问题。
答案 1 :(得分:2)
sitesbyjoe的答案很好,但是......你不需要在控制器中进行第一次分配(第二块代码的第2行),只调用该函数并在其中分配一个值是enogh
厂
factory.getFamily2 = function() {
return $http.get('/family.json').then(function(result) {
family = result.data;
return family;
});
}
在控制器
中 function init() {
simpleFactory.getFamily2().then(function(data) {
$scope.family = data;
});
}
答案 2 :(得分:0)
仅供参考 - 我最终在工厂换货了:
factory.getFamily2 = function() {
return $http.get('/family.json').then(function(result) {
family = result.data;
return family;
});
}
并在控制器中:
function init() {
$scope.family = simpleFactory.getFamily2().then(function(data) {
$scope.family = data;
});
}
通过这些更改,我获得了远程数据,视图过滤工作正常,一切都很顺利。