【问题标题】:Angular's two way binding on ui-select2Angular 在 ui-select2 上的双向绑定
【发布时间】:2014-09-02 14:04:06
【问题描述】:

简单的问题,可能已经讨论过很多次了,但是我在这个简单的问题上找不到合适的解决方案。

问题:
对选定项目的修改对视图没有影响(应该如此)。

控制器:

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


我怎样才能使双向绑定工作?

【问题讨论】:

    标签: angularjs ui-select2


    【解决方案1】:

    从第 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 将源集合复制回自身。

    【讨论】:

    • 非常感谢...我又发了一个fiddle 来证明! select2 指的是 select2.js 的编辑版本
    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 2020-09-12
    • 2019-03-05
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多