在我的控制器中我有一个模型和一个这样的数组:
$scope.myModel = {
title:'title',
descr:'descr',
id: ''
};
$scope.arrayOption = [
{id: 1, text:"aaaaaaa"},
{id: 2, text:"bbbbbbb"}
];
在我的html文件中,我有这个选择输入
<select ng-model="myModel.id" ng-options="item.text for item in arrayOption"></select>
当我更改所选值时,我想在arrayOption中使用id值更新我的模型(myModel.id)。
使用上面的代码,myModel.id的内容是整个对象,而不仅仅是id字段。
请帮帮我吗?
这是 plnkr demo
答案 0 :(得分:0)
您应该更改ng-model绑定以将所选值直接绑定到模型,而不是其属性。
<select ng-model="myModel" ng-options="item.text for item in arrayOption">
</select>
请参阅plunkr。
如果这不是您想要的,并且您想要映射ID和文本,则应考虑将arrayOptions从text更新为title以匹配模型的预期结构。
<select ng-options="item as item.title for item in arrayOption track by item.id"
ng-model="myModel">
</select>
答案 1 :(得分:0)
您正在更换模型!
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.2.19" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js" data-require="angular.js@1.2.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
{{myModel.title}}
<br>
{{myModel.descr}}
<br>
{{myModel.id}} <br>
<select ng-change="change(temp)" ng-model="temp" ng-options="item.text for item in arrayOption"></select>
</body>
</html>
和JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.myModel = {
title:'title',
descr:'descr',
id: ''
};
$scope.arrayOption = [
{id: 1, text:"aaaaaaa"},
{id: 2, text:"bbbbbbb"}
];
$scope.change = function(temp){
$scope.myModel.id = temp.id;
}
});
答案 2 :(得分:0)
或者更容易!!!
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.2.19" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js" data-require="angular.js@1.2.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
{{myModel.title}}
<br>
{{myModel.descr}}
<br>
{{myModel.id}} <br>
<select ng-change="myModel.id = temp.id" ng-model="temp" ng-options="item.text for item in arrayOption"></select>
</body>
</html>
答案 3 :(得分:0)
我尝试了这个解决方案:
<select ng-model="myModel.id" ng-options="item.id as item.text for item in arrayOption"></select>
效果很好!这里是updated plunker。
谢谢大家!