简单的问题,可能已多次讨论过,但我无法在这个简单的问题上找到合适的解决方案。
问题:
对所选项目的修改对视图没有影响(它应该)。
控制器:
var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope) {
$scope.selectedDaltons = [4]; // Averell is preselected (id:4)
$scope.daltons = [
{ id: 1, name: 'Joe' },
{ id: 2, name: 'William' },
{ id: 3, name: 'Jack' },
{ id: 4, name: 'Averell' },
{ id: 5, name: 'Ma' }
];
$scope.changeAverellsName = function() {
// Fiddle's issue!!
// observe, that the selected item on the view does not change!!
$scope.daltons[3].name = "Idiot";
};
};
查看:
<div ng-controller="MyCtrl">
<!-- changing model via click -->
<button ng-click="changeAverellsName()">change Averell's name to 'Idiot'</button>
<!-- selected items are not binded to the model -->
<select multiple ui-select2 class="form-control" id="70.1.6.3" data-ng-model="selectedDaltons">
<option data-ng-repeat="dalton in daltons" value="{{dalton.id}}" text="">{{dalton.name}}</option>
</select>
<!-- this list is for assure, that two way binding works -->
<ul>
<li data-ng-repeat="dalton in daltons">{{dalton.name}}</li>
</ul>
</div>
如何进行双向约束工作?
答案 0 :(得分:3)
从第134行的源代码here开始观察源集合,它只是观察要更改的集合(删除或添加的项目),而不是要更改的项目属性的值。要观察项目属性更改,手表需要编码为:
scope.$watch(watch, function (newVal, oldVal, scope) {
if (angular.equals(newVal, oldVal)) {
return;
}
// Delayed so that the options have time to be rendered
$timeout(function () {
elm.select2('val', controller.$viewValue);
// Refresh angular to remove the superfluous option
controller.$render();
if(newVal && !oldVal && controller.$setPristine) {
controller.$setPristine(true);
}
});
}, true);
注意watch函数末尾的'true'。要解决这个问题,您需要使用map将源集合复制回自身。