This article mainly introduces AngularJS conversion response content. If you need it, you can refer to the response content obtained from the Remote API, which is usually in json format, sometimes, you need to convert the obtained content, such as removing unnecessary fields and alias the fields.
This article describes how to implement AngualrJS.
Take data from the controller on the home page.
Above, the userName and url fields are converted from the source data. Maybe the userName corresponds to the fullName in the source data, and there are more fields in the energy data.
In AngularJS, it is a good habit to sort out the relationship between modules clearly, for example, sort them as follows:
angular.module('publicapi.controllers',[]);angular.module('publicapi.services',[]);angular.module('publicapi.transformers',[]);angular.module('publicapi',['publicapi.controllers','publicapi.services','publicapi.transformers'])
The data is still from the controller:
angular.module('publicapi.controllers').controller('controllers.View',['$scope', 'service.Api', function($scope, api){$scope.repos = api.getUserRepos("");}]);
The controller depends on the service. Api service.
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;}};}])
In the $ http service, the transformResponse field is used to convert the data source. Services. Api relies on services. transformer. ApiResponse, which converts data sources.
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;};});
The preceding figure uses underscore to map the data source.