gpt4 book ai didi

javascript - Angular : Passing data back to my controller from a factory ajax call

转载 作者:可可西里 更新时间:2023-11-01 16:28:25 26 4
gpt4 key购买 nike

我一直在玩 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com