最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

AngularJS轉(zhuǎn)換響應內(nèi)容

 更新時間:2016年01月27日 11:31:37   投稿:mrr  
這篇文章主要介紹了AngularJS轉(zhuǎn)換響應內(nèi)容 的相關資料,需要的朋友可以參考下

從遠程API獲取到的響應內(nèi)容,通常是json格式的,有時候需要對獲取到的內(nèi)容進行轉(zhuǎn)換,比如去除某些不需要的字段,給字段取別名,等等。

本篇就來體驗在AngualrJS中如何實現(xiàn)。

在主頁面,還是從controller中拿數(shù)據(jù)。

<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字段是從源數(shù)據(jù)中轉(zhuǎn)換而來的,可能userName對應源數(shù)據(jù)中的fullName,可能源數(shù)據(jù)中有更多的字段。

在AngularJS中,把module之間的關系梳理清楚是一種很好的習慣,比如按如下方式梳理:

angular.module('publicapi.controllers',[]);
angular.module('publicapi.services',[]);
angular.module('publicapi.transformers',[]);
angular.module('publicapi',[
'publicapi.controllers',
'publicapi.services',
'publicapi.transformers'
]) 

數(shù)據(jù)還是從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字段就是用來轉(zhuǎn)換數(shù)據(jù)源的。services.Api依賴于services.transformer.ApiResponse這個服務,在這個服務力完成對數(shù)據(jù)源的轉(zhuǎn)換。

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對數(shù)據(jù)源進行map轉(zhuǎn)換。

相關文章

最新評論

库伦旗| 启东市| 英吉沙县| 滦南县| 高陵县| 石景山区| 怀来县| 南宫市| 仁化县| 临泉县| 策勒县| 仪陇县| 嘉荫县| 浦县| 革吉县| 砚山县| 修水县| 林周县| 台州市| 湘阴县| 长子县| 东平县| 咸阳市| 汉川市| 惠东县| 绵竹市| 江达县| 呼图壁县| 武义县| 新巴尔虎左旗| 东海县| 商洛市| 麻栗坡县| 会同县| 年辖:市辖区| 年辖:市辖区| 云龙县| 茂名市| 乐平市| 焉耆| 磐石市|