(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', [function() {
this.model = {
person: {
titleId: 4
}
}
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller as nb">
<select ng-model="nb.model.person.titleId">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<p>{{nb.model.person.titleId}}</p>
</div>
</div>
当我选择A
,B
,C
或D
时,模型值会按预期更新。 person
的{{1}}值介于1和4之间。
但是在使用titleId
。
titleId
未将选择设置为正确的值。模型绑定似乎是单向工作,而不是2路?
有一种简单的方法可以解决这个问题吗?
答案 0 :(得分:3)
您应将其设为"4"
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', [function() {
this.model = {
person: {
titleId: "4"
}
}
}]);
})(window.angular);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller as nb">
<div class="input-group">
<select class="form-control" id="Person_TitleId" name="Person.TitleId" ng-model="nb.model.person.titleId">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
</div>
</div>
&#13;
但我建议您使用ngOptions
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', [function() {
this.model = {
person: {
titleId: 4
}
}
this.options = [{
label: 'A',
titleId: 1
}, {
label: 'B',
titleId: 2
}, {
label: 'C',
titleId: 3
}, {
label: 'D',
titleId: 4
}]
}]);
})(window.angular);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller as nb">
<select ng-model="nb.model.person" ng-options="a.label for a in nb.options track by a.titleId ">
</select>
<p>{{nb.model.person}}</p>
</div>
&#13;