包含HTTP服务角get调用与吴先生重复工作 [英] Angular service containing http get call not working with ng-repeat
问题描述
我有一个角控制器调用服务。该服务是负责从JSON文件返回数据。
I have an angular controller that calls a service. The service is responsible for returning data from a json file.
控制器:
function projectController($scope, ajaxServices) {
$scope.projects = ajaxServices.getProjects();
}
服务:
projectManagerApp.factory('ajaxServices', function ($http) {
return {
getProjects : function () {
$http.get('projects.json', { data: {} }).success(function (data) {
if (window.console && console.log) {
console.log("objects returned: " + data.length); // shows # of items
}
return data //nothing ng-repeated, no console errors.
})
// Exact same data from json file hard-coded, works fine
// when not commented out.
// return [{ "id": 1, "name": "Project 1 }, { "id": 2, "name": "Project 2" }]
}
}
});
HTML: NG-重复=工程项目
在成功的功能,我可以看到在控制台日志返回的数据,但如果我尝试将数据返回我的页面上的NG-重复ul元素为空。在相同的服务,如果我只是返回记录到控制台硬codeD相同的数据(外成功的功能,当然它工作得很好。
In the success function I can see the data returned in the console log but if I try to return the data the ng-repeat ul element on my page is empty. In the same service if I simply return the same data logged to the console hard coded (outside of the success function, of course it works just fine.
如何使用我的ajax调用我的数据返回到NG-重复?
How can I return the data into the ng-repeat using my ajax call?
我只是作为新Plunker因为我的角,但这里是我在尝试普拉克:
http://plnkr.co/edit/ALa9q6
I'm just as new to Plunker as I am Angular but here is my attempt at a Plunk: http://plnkr.co/edit/ALa9q6
推荐答案
$ HTTP
是异步的,因此调用 getProjects
将返回什么。使用 $ Q
您可以收到一个实例将接收数据的承诺时可用。
$http
is asynchronous, therefore the call to getProjects
will return nothing. Using $q
you can receive an instance to a promise which will receive the data when available.
使用$ Q
下面通过实例 $ Q
:
http://plnkr.co/edit/U72oJblvrVEgYt2mTmU2?p=$p$pview一>
使用$资源
另外,你可以使用 $资源
特别是如果你的服务器code是REST风格,这需要增加在脚本以下依赖性: // ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular-resource.js
Alternatively, you can use $resource
especially if your server code is RESTful, which requires adding the following dependency in your scripts:
//ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular-resource.js
这是您的code的第一次审查中使用 $资源
: http://plnkr.co/edit/tLOAaXZHdGgWOok3Sdc8?p=$p$pview
This is a 1st review of your code to use $resource
: http://plnkr.co/edit/tLOAaXZHdGgWOok3Sdc8?p=preview
但是你可以简化和更多的这种缩水:
http://plnkr.co/edit/pKO6k6GxJ1RlO8SNvqUo?p=$p$pview一>
But you can simplify and shrink it more to this: http://plnkr.co/edit/pKO6k6GxJ1RlO8SNvqUo?p=preview
这是新的 app.js
文件:
angular.module('app', ['ngResource'])
.factory('ProjectsService', ['$resource', function($resource) {
return $resource('projects.json');
}])
.controller('ProjectsController', ['ProjectsService', '$scope', function(ProjectsService, $scope) {
$scope.projects = ProjectsService.query();
}]);
查找关于 $资源更多信息
在这里:
http://docs.angularjs.org/api/ngResource 。$资源
这篇关于包含HTTP服务角get调用与吴先生重复工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!