Usage
$http(config);
Arguments
config
Object describing the request to be made and how it should be processed. The object has following properties: method – {string} – HTTP method (e.g. 'GET', 'POST', etc) url – {string|TrustedObject} – Absolute or relative URL of the resource that is being requested; or an object created by a call to $sce.trustAsResourceUrl(url). params – {Object.<string|Object>} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters. data – {string|Object} – Data to be sent as the request message data.
example:
var req = { method: 'POST', url: 'http://example.com', headers: { 'Content-Type': undefined }, data: { test: 'test' }}$http(req).then(function(){...}, function(){...});
摘自angular1.x官網:https://docs.angularjs.org/api/ng/service/$http
其中設定對象可以包含以下主要的鍵:
①method
可以是:GET/DELETE/HEAD/JSONP/POST/PUT
②url:絕對的或者相對的請求目標
③params(字串map或者對象)
這個鍵的值是一個字串map或對象,會被轉換成查詢字串追加在URL後面。如果值不是字串,會被JSON序列化。
?
④data(字串或者對象)
這個對象中包含了將會被當作訊息體發送給伺服器的資料。通常在發送POST請求時使用。
從AngularJS 1.3開始,它還可以在POST請求裡發送位元據。要發送一個blob對象,你可以簡單地通過使用data參數來傳遞它。
?
在控制器中使用$http
var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.resizeColumns', 'ui.grid.moveColumns']); app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) { $scope.gridOptions = { enableSorting: true, columnDefs: [ { field: 'name', minWidth: 200, width: 250, enableColumnResizing: false }, { field: 'gender', width: '30%', maxWidth: 200, minWidth: 70 }, { field: 'company', width: '20%' } ] }; $http.get('/data/100.json') .success(function(data) { $scope.gridOptions.data = data; });}]);
摘自angular ui grid: http://ui-grid.info/docs/#/tutorial/204_column_resizing
獲得資料並對資料進行過濾
$http.get('/data/100.json') .success(function(data) { data.forEach( function setGender( row, index ){ row.gender = row.gender==='male' ? '1' : '2'; }); $scope.gridOptions.data = data; });}]).filter('mapGender', function() { var genderHash = { 1: 'male', 2: 'female' }; return function(input) { if (!input){ return ''; } else { return genderHash[input]; } };});