2015-02-10 71 views
-3

我的控制器:AngularJS - 如何從GET方法獲取數據

angular.module('apartmentCtrl', []) 

.controller('ApartmentController', function ($scope, $http, Apartment) { 
    $scope.loading = true; 

    $scope.myLocation = ''; 

    Apartment.get($scope.myLocation).success(function (data) { 
     $scope.apartments = data; 
     $scope.loading = false; 
    }); 
}); 

我的服務 angular.module( 'apartmentService',[])

.factory('Apartment', function ($http) { 
    return { 
     get: function (myLocation) { 
      //return $http.get('/api/apartments'); 
      return $http({ 
       method: 'GET', 
       url: '/api/apartments', 
       //headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
       params: {location: myLocation} 
      }); 
     } 
    }; 
}); 

我的HTML:

<input type="text" name="myLocation" class="form-control" ng-model="myLocation"> 

如何從AngularJS的GET方法獲取數據並將其傳遞給params

+2

請出示你的代碼。你使用Angular提交表單嗎? – 2015-02-10 02:20:08

+0

你可以使用'$ http'來做到這一點。 http://www.w3schools.com/angular/angular_http.asp – 2015-02-10 02:32:05

+0

你必須在控制器中使用'$ http'服務。請顯示您的代碼 – nosthertus 2015-02-10 02:32:58

回答

1

如果你想從窗體傳遞一些值作爲「位置」,你應該將它綁定到你的模型,並明確地將它傳遞給你的工廠get函數。

我在這裏有一個工作示例,它只是一個窗口提示,顯示您輸入的數據,而不是$ http調用,但想法是相同的。

http://plnkr.co/edit/fRra6RfQrSZb8rzrm4XF?p=preview

HTML:

<!DOCTYPE html> 
<html ng-app="plunker"> 

    <head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script>document.write('<base href="' + document.location + '" />');</script> 
    <link rel="stylesheet" href="style.css" /> 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script> 
    <script src="app.js"></script> 
    </head> 

    <body ng-controller="MainCtrl"> 
    <p>Hello {{name}}!</p> 

    <form ng-submit="getIt()"> 
     <input type="text" ng-model="myLocation"/> 
     <input type="submit"/> 
    </form> 

    </body> 

</html> 

的Javascript:

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope, Apartment) { 
    $scope.name = 'World'; 
    $scope.myLocation = 'Hollywood'; 

    $scope.getIt = function() { 
    Apartment.get($scope.myLocation); 
    } 
}); 

app.factory('Apartment', function ($window) { 
     return { 
      get: function (whatLocation) { 
       $window.alert(whatLocation); 
      } 
     }; 
    }); 
+0

我無法獲得'myLocation'的價值:( – 2015-02-10 04:55:54

+0

謝謝。它有效。但我有一個新問題。假設我有一個URL:'http://myproject.com/apartments?location=&arrival=1/15/2015&departure = 2/1/2015&room = 1'。我提交時如何獲取參數'arrival','departure','room'並將它們附加到表單數據中。 – 2015-02-10 15:40:38

+1

完全一樣,通過所有你需要的參數以及你的$ http將它們添加到你發送的參數中,所以你的公寓獲取函數可能看起來像:'get:function(myLocation,arrival,departure,room)...',在這種方法中, d打電話給你的web服務:'params:{location:myLocation,arrival:arrival,departure:departure,rooms:rooms}' – 2015-02-10 16:54:15

相關問題