所以我在我的ngOptions
应用程序中同时使用了ngModel
和AngularJS
。出于某种原因,我无法让模型更改为所选值。
$scope.selected
保持其初始值
$scope.options = [];
$scope.selected;
$scope.save = function(){
var item = $scope.selected;
console.info('item : ', item)
console.info('save : ', $scope.selected,
'\n', $scope.options)
};
function setOptions(options){
for(var i = 0; i < options.length; i++){
var option = {
label: options[i].tyTxt,
value: options[i].tyID
};
if(i === 0){
$scope.selected = option.value;
}
$scope.options.push(option);
}
}
<select ng-options="item.value as item.label for item in options track by $index" ng-model="selected"></select>
<span ng-click="save()">
save
</span>
的修改
我甚至试过这个:
function setOptions(options){
for(var i = 0; i < options.length; i++){
var option = {
label: options[i].tyTxt,
value: options[i].tyID
};
if(i === 0){
$scope.selected = option.value;
}
$scope.options.push(option.value);
}
}
<select ng-options="item for item in options" ng-model="selected"></select>
但结果相同
答案 0 :(得分:0)
如果您正在使用angularjs,则无需在代码中使用 setOptions(),而是从后端返回json响应并初始化数组,如下所示。
<div ng-controller="MyCtrl">
<select ng-options="item.value as item.label for item in options" ng-model="selected"></select>
<p>
<b>Selected value = </b>{{selected}}
</p>
<button ng-click="save()">
save
</button>
</div>
这是控制器代码
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.save = function(){
var item = $scope.selected;
console.info('item : ', item)
console.info('save : ', $scope.selected,
'\n', $scope.options)
};
$scope.options = [{label:"data-1",value:1},{label:"data-2",value:2},{
label:"data-3",value:3}];
}
在上面的angularjs代码中, $ scope.options 是为样本声明的静态。你只需将响应返回到此 [{标号: “数据1”,值:1},{标签: “数据2”,值:2},{ label:“data-3”,value:3}]并将其分配给 $ scope.options