对不起,如果这已经得到了回答,但有角度的md-select的行为让我开始喝酒。
我遇到的情况是我创建了一个包含一些字段和一个select元素的对象数组。我想预先选择select元素中的值,并且我得到了奇怪的行为。
这是HTML(使用角度材质):
<md-list>
<md-list-item ng-repeat="condition in conditions track by $index">
<div layout="row" flex>
<div flex="5">
</div>
<div flex="25">
<md-input-container>
<label>From</label>
<input required type="number" name="from" minvalue=0 maxvalue="100" ng-model="condition.from">
</md-input-container>
</div>
<div flex="5">
</div>
<div flex="25">
<md-input-container>
<label>To</label>
<input required type="number" name="to" minvalue=0 maxvalue="100" ng-model="condition.to">
</md-input-container>
</div>
<div flex="5">
</div>
<div flex="25">
<md-input-container>
<label>Select Question</label>
<md-select ng-model="condition.question[$index]" ng-model-options="{trackBy: '$value._id'}" required name="cQuestion">
<md-option ng-repeat="question in questions | orderBy : '_id'" ng-selected="{{condition.question._id === question._id ? true : false}}" ng-value={{question}}>
{{question.title}}
</md-option>
</md-select>
</md-input-container>
</div>
<div flex="5">
</div>
</div>
</md-list-item>
</md-list>
这里是创建我试图测试的值的js:
$scope.questions = [
{title: 'Question 1', qtype: 1, _id:1},
{title: 'Question 2', qtype: 2, _id:2},
{title: 'Question 3', qtype: 3, _id:3},
{title: 'Question 4', qtype: 4, _id:4},
{title: 'Question 5', qtype: 5, _id:5}
];
$scope.conditions = [];
var condition = {};
condition.from = '';
condition.to ='';
condition.question = {title: 'Question 2', qtype: 2, _id:3};
$scope.conditions.push(condition);
condition.from = '';
condition.to ='';
condition.question = {title: 'Question 5', qtype: 5, _id:5};
$scope.conditions.push(condition);
如果你运行它,你会发现两行都选择了问题5。看起来这个模型很困惑。
有关解决此问题需要采取哪些措施的想法?
答案 0 :(得分:3)
您使用旧的&#34;条件&#34; -Object两次。但是你必须在推送后创建一个新的&#34;条件&#34; -Object。
var condition = {};
condition.from = '';
condition.to ='';
condition.question = {title: 'Question 2', qtype: 2, _id:3};
$scope.conditions.push(condition);
condition = {}; // <= this line was added
condition.from = '';
condition.to ='';
condition.question = {title: 'Question 5', qtype: 5, _id:5};
$scope.conditions.push(condition);