首頁 > 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學習者快速成長!