AngularJS将变量传递给工厂

时间:2015-05-18 18:24:44

标签: javascript html angularjs

我有以下select列表:

<select name="make" class="form-control" ng-model="selectCity">
    <option value="Kannur">Kannur</option>
    <option value="Agra">Agra</option>
    <option value="Ahemedabad">Ahemedabad</option>
    <option value="Bangalore">Bangalore</option>
    <option value="Chennai">Chennai</option>
    <option value="Mumbai">Mumbai</option>
</select>

当我更改所选选项时,我需要将ng-modelselectCity传递给调用API的工厂:

工厂:

carPriceApp.factory('APIservices', function($http){

    APIcarModels = {};
    APIcarModels.getAPIcarModels = function(){
        return $http.get('/carprices3/api/apiData'+ selectCity +'.js')
    }
    return APIcarModels;

});

4 个答案:

答案 0 :(得分:11)

我解决了你的问题,在这里写html

<div ng-controller="myCtrl">
  <select ng-change="changeCity()" name="make" class="form-control" ng-model="selectCity">
    <option value="Kannur">Kannur</option>
    <option value="Agra">Agra</option>
    <option value="Ahemedabad">Ahemedabad</option>
    <option value="Bangalore">Bangalore</option>
    <option value="Chennai">Chennai</option>
    <option value="Mumbai">Mumbai</option>
  </select>
</div>

和javascript在这里

var app = angular.module('myApp', []);
app.factory('APIservices', function($http) {
  var APIcarModels = {};
  APIcarModels.getAPIcarModels = function(selectCity) {
    alert(selectCity);
    return $http.get('/carprices3/api/apiData'+ selectCity +'.js')
  }
  return APIcarModels;

});

function myCtrl($scope, APIservices) {
  $scope.changeCity = function() {
    APIservices.getAPIcarModels($scope.selectCity);
  };

}

工作示例Here

答案 1 :(得分:2)

您可以使用选择列表中的cp /etc/python3start /etc/pythonstart 属性,然后调用您的API。您还需要在ng-change函数中使用参数:

你的标记就像:

getAPIcarModels

在你的控制器中:

<select name="make" class="form-control" ng-model="selectCity" ng-change="selectMake()">

最后,你的工厂:

$scope.selectMake = selectMake() {
    APIservices.getAPIcarModels($scope.selectCity);
}

答案 2 :(得分:1)

您需要添加ng-change="changeCity(selectCity)"

之类的内容

请参阅以下文章以获取示例和更多信息

http://plnkr.co/edit/0IVNLHiw3jpz4zMKcB0P?p=preview
http://stackoverflow.com/questions/26485346/how-do-i-get-the-ng-model-of-a-select-tag-to-get-the-initially-selected-option    
http://stackoverflow.com/questions/25935869/id-as-ng-model-for-select-in-angularjs

答案 3 :(得分:0)

或者:使用ng-options

视图:

<div ng-app='App' ng-controller="AppCtrl">
    <select ng-model="selectedCity" ng-options="city.name for city in cities">
</select>
   Selected City is  {{selectedCity.name}}
</div>

JS:

angular.module('App', [])
.controller('AppCtrl', function($scope) {

    $scope.cities = [
        {name: 'Chicago'},
        {name: 'London'}
     ];
    $scope.selectedCity = '';   
});

工作示例:https://jsfiddle.net/pz9f093e/