Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS pass variable into factory

I have the following select list:

<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>

When I change the selected option I need to pass the ng-model, selectCity into a factory which calls an API:

The factory:

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

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

});
like image 217
Hunter Avatar asked May 18 '15 18:05

Hunter


1 Answers

I solved your problem write html here

<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>

and javascript here

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);
  };

}

Working example Here

like image 112
vamsikrishnamannem Avatar answered Oct 06 '22 00:10

vamsikrishnamannem