AngularJs - ng-options not binding after ajax call

爷,独闯天下 提交于 2019-12-10 04:06:39

问题


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?


回答1:


@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.
:)



来源:https://stackoverflow.com/questions/22348886/angularjs-ng-options-not-binding-after-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!