【问题标题】:AngularJs - ng-options not binding after ajax callAngularJs - ajax调用后ng-options不绑定
【发布时间】:2014-04-16 10:22:06
【问题描述】:

我尝试在 ajax 调用后更改 ng-options 的选定索引,但不会更改。

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

这是我的 API 发送的数据。

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

怎么了?如何自动更改 ng-options 中的选择?

【问题讨论】:

  • 你有ng-options="...in the_formula",然后是$scope.The_Formula = ...,然后是$scope.formula = ...。这些是指同一个变量吗?它应该拼写相同,区分大小写。
  • 哎呀,抱歉编辑错误。但它在实际代码中工作。

标签: javascript jquery ajax angularjs ng-options


【解决方案1】:

@reptildarat

你好,

当我使用 select 和 ng-option 时,我也陷入了同样的境地。 :)

你必须做什么-

在从 ajax 调用中检索到数据并完成绑定后设置“foo.formula”的值。 原因 - 呈现 Html 时。它在选择标签中绑定“foo.formula”。那时没有填充任何项目。一段时间后,项目从后面(js)填充,并且没有为该 ng-model 触发触发器。

经过一番努力,我找到了这个-

例子-

这是你需要在 js 中做的事情。

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

这是我的 HTML-

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

希望这会有所帮助。
让我知道您的疑虑。
:)

【讨论】:

  • 嗨,还是没有运气..我虽然是因为承诺,但事实并非如此。所以它一定是关于我使用的数据。我用我使用的数据更新了问题。希望您能提供帮助。
  • 不要与 - ng-model ="foo.formula" 绑定。尝试使用 - ng-model ="selectedformula" 绑定它。
  • ng-change 中的函数调用采用相同的值 ng-model,因此当您使用 ng-change 选择其他值时,上述解决方案不起作用。 ng-model="selectedOption" ng-change="itemSelected(selectedOption)",这不起作用。
【解决方案2】:

http 调用后,拨打$scope.selectedOption = options[0]

当您使用ng-change 时,这可能是更具体的解决方案。

<select ng-model="selectedOption" class="form-control" ng-change="metaTypeSelected(selectedOption)">
    <option 
        ng-selected="{{selectedOption}}" 
        ng-repeat="selectedOption in options track by $index"
        value="{{selectedOption}}">
        {{selectedOption}}
    </option>
</select>

ng-modelng-repeatng-change 中使用selectedOption

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2018-06-21
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多