简体   繁体   中英

Two way databinding in Select2 for AngularJS doesn't work in angular 1.2.13

I'm basing my question on a similar question asked here: Two way databinding in Select2 for AngularJS doesn't work

This question was answered and was supplied with a working plunker: http://plnkr.co/edit/MKy2IU?p=preview

The main code was a select box:

<select ui-select2="{width: 'element'}" style="width: 200px" placeholder="All" ng-model="chosenItem">
        <option value=""></option>
        <option ng-repeat="item in filterItems" value="{{item.id}}">{{item.text}}</option>
      </select>

and a function which updates the select control. This works well in the plunker.

I forked the plunker and only changed the angular version from: 1.0.7 to: 1.2.13 (which i'm using)

Here is the forked plunker http://plnkr.co/edit/bcowo3bHKC2XvWDrv6V2?p=preview using angular 1.2.13, you can see in the plunker that the model is updated however the view is not affected, and moreover when you open the select box you see the value is selected but not chosen.

Any idea how to make that work?

I have not used select2 plugin, but it seems like with your angular update, your select2 directive's priority needs to be higher than ng-model 'priority which is 0 , so i just provided a priority 1 for the directive and it works now.

In the ui-select2 change:-

angular.module('ui.directives').directive('uiSelect2', ['ui.config', '$timeout', function (uiConfig, $timeout) {
  var options = {};
  if (uiConfig.select2) {
    angular.extend(options, uiConfig.select2);
  }
  return {
    require: '?ngModel',
    priority: 1,  //<--- Here

Demo

And if you really don't want to touch the plugin source (which i would recommend for any later upgrades), in your app just set the priority as configuration, and remove it once you get a working version of this directive. Also verify if they have a newer version where it has been fixed.

   //Remove later once plugin is fixed
   app.config(function($provide){
      return $provide.decorator('uiSelect2Directive', ['$delegate', function($delegate) {
        $delegate[0].priority = 1; //Just set the priority
        return $delegate;
    }])});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM