2014-09-02 46 views
2

簡單的問題,可能討論了很多次,但我無法在這個簡單的問題上找到合適的解決方案。Angular的雙向綁定ui-select2

問題:
對選定項目的修改對視圖(它應該)沒有影響。

控制器:

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> 


Here as jsfiddle


我怎樣才能讓雙向綁定工作?

回答

2

源自線上的源代碼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); 

注意手錶功能結束時的「真」。爲了解決這個問題,您需要使用map將您的源集合複製回自己。

+0

非常感謝你...我做了另一個[小提琴](http://jsfiddle.net/Jobacca/x8ccty6x/)來證明它! select2引用了select2.js的編輯版本 – Jobacca 2014-09-08 13:56:49