Patan
Patan

Reputation: 17893

calling a HTTP get method to populate the result in drop down using angular JS

I have all controllers defined at one place.

 $routeProvider.when(pages.hello, 
    {
      templateUrl: 'test/hello.html', 
      controller: 'myController',
      access: access.anon,
      helloPage: 'arf'
    });

My hello.html looks like this.

<select name="chooseFunc" data-ng-model="choosenFunction"  class="input-xlarge ng-pristine ng-valid" data-ng-click="fetchID()"  data-ng-change="update(choosenFunction)">
            <option value="ABCD">ABCD</option>
            <option value="CDEF">CDEF</option>            
        </select> 

Now I want to call a http get method "/abc/hello" to populate the drop down like ABCD, CDEF values based on it.

I have written some thing like this.

 $scope.fetchID = function() {
        console.log("hello in fectch id"); 
        $http.get('/abc/hello').success(successCallback).error(error);        
      };

My function is not getting called. Could some help me with the following.

  1. Calling fecthID() function on page load.
  2. fechID() function should populate the options in select element.

I am new here. Can some one help me.

Upvotes: 0

Views: 2322

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

I would write controller like:

function myController($scope,$http) {

    $scope.values = [{id:"ABCD",Name:"David"},{id:"CDEF",Name:"John"}];

    $scope.selectedItem = $scope.values[0].id;

     $scope.fetchID = function() {

        $http.get('/abc/hello').success(
            function(data, status, headers, config){
                $scope.values.push(data);// play here
            }) 
        .error(error);          
      };

 $scope.fetchID(); // call
}

and hello.html with init first combo value:

   <select name="chooseFunc"        
    ng-model="selectedItem"        
     ng-options="selectedItem.id as selectedItem.id for selectedItem in values"          
     class="input-xlarge ng-pristine ng-valid"          
     data-ng-click="fetchID()"          
      data-ng-change="update(choosenFunction)"          
      ></select>

Upvotes: 1

Satpal
Satpal

Reputation: 133433

You can use ng-options to populate select like

<select ng-model="mySelecetdValue" ng-options="item for item in items">
</select>

To Call fecthID(), Just call it like

$scope.fetchID()

And Populate items in successCallback function

Upvotes: 1

Related Questions