首页 > web前端 > js教程 > 正文

AngularJS转换响应内容_AngularJS

WBOY
发布: 2016-05-16 15:17:41
原创
1297 人浏览过

从远程API获取到的响应内容,通常是json格式的,有时候需要对获取到的内容进行转换,比如去除某些不需要的字段,给字段取别名,等等。

本篇就来体验在AngualrJS中如何实现。

在主页面,还是从controller中拿数据。

<body ng-app="publicapi">
<ul ng-controller="controllers.View">
<li ng-repeat="repo in repos">
<b ng-bind="repo.userName"></b>
<span ng-bind="repo.url"></span>
</li>
</ul>
</body> 
登录后复制

以上,userName, url字段是从源数据中转换而来的,可能userName对应源数据中的fullName,可能源数据中有更多的字段。

在AngularJS中,把module之间的关系梳理清楚是一种很好的习惯,比如按如下方式梳理:

angular.module('publicapi.controllers',[]);
angular.module('publicapi.services',[]);
angular.module('publicapi.transformers',[]);
angular.module('publicapi',[
'publicapi.controllers',
'publicapi.services',
'publicapi.transformers'
]) 
登录后复制

数据还是从controller中来:

angular.module('publicapi.controllers')
.controller('controllers.View',['$scope', 'service.Api', function($scope, api){
$scope.repos = api.getUserRepos("");
}]); 
登录后复制

controller依赖于service.Api这个服务。

angular.module('publicapi.services').factory('services.Api',['$q', '$http', 'services.transformer.ApiResponse', function($q, $http, apiResponseTransformer){
return {
getUserRepos: function(login){
var deferred = $q.defer();
$http({
method: "GET",
url: "" + login + "/repos",
transformResponse: apiResponseTransformer
})
.success(function(data){
deferred.resolve(data);
})
return deferred.promise;
}
};
}]) 
登录后复制

而$http服务中的transformResponse字段就是用来转换数据源的。services.Api依赖于services.transformer.ApiResponse这个服务,在这个服务力完成对数据源的转换。

angular.module('publicapi.transformers').factory('services.transformer.ApiResponse', function(){
return function(data){
data = JSON.parse(data);
if(data.length){
data = _.map(data, function(repo){
return {userName: reop.full_name, url: git_url};
})
}
return data;
};
}); 
登录后复制

以上,使用了underscore对数据源进行map转换。

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!