Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs - ng-options not binding after ajax call

I try to change the selected index of ng-options after ajax call, but it won't change.

//Html Section...

<select id="fooId" ng-model ="foo.formula"
   ng-options="formulas as name for (formulas, name) in the_formula"></select>

//End Html Section...


//js file...

//get list of formula from server...
TheSource.Get.then(function(response){
    $scope.the_formula = response.the_formula;
});


//do something awesome, then..
//binding data from server...

TheData.Get.then(function(response){
    //binding the data to view...
    //all of the element is binding, except the ng-options part..
    $scope.foo = response; 

    //not working..
    //$scope.formula = response.formulaId //it is return integer ID like (1, 2, 3, etc..)
});

// End js file...

And this is the data that send by My API.

{ 
   "the_formula":{
     "123":"formula1",
     "124":"formula2"
   }
}

What's wrong? How To Automatically change selection in ng-options?

like image 333
reptildarat Avatar asked Mar 12 '14 10:03

reptildarat


1 Answers

@reptildarat

Hello,

I too was stuck in the same situation when I was working with select and ng-option. :)

What you will have to do-

Set the value of "foo.formula" after the data in retrieved from the ajax call and binding is done. Reason- When the Html is being rendered. It binds "foo.formula" in the select tag. At that time there is no items populated. After sometime the items are populated from behind (js) and no trigger is fired for that ng-model.

After a lot of effort I found this-

Example-

Here is what you need to do in js.

   .success(function (data) {  
            $scope.$emit('HideLoading');  
            $scope.departments = data.DepartmentsGetResult;  
            $scope.selectedDepartment = item.DepartmentId;  

Here is my HTML-

<select   
   data-ng-model="selectedDepartment"   
   data-ng-options="dept.DepartmentId as dept.Title for dept in departments" >  
 </select>  

Hope this will help.
Let me know your concerns.
:)

like image 73
Manish Gupta Avatar answered Nov 05 '22 06:11

Manish Gupta