yuxia1991
yuxia1991

Reputation: 1

Select2 view doesn't change after changing ng-model

I was working on creating a element with select2 treatment. I created a angular directive for select2 dropdown. However, if I change the ng-model after the directive rendered, the view won’t get update.

Following is the link for a simple example in Jsfiddle: http://jsfiddle.net/odiseo/zrchy7w0/5/

<div ng-app="miniapp" ng-controller="Ctrl">
<select ng-model="selectedOption" wb-select2 ng-options="k as v for (k, v) in optionList" select-width="300px"></select>
<button ng-click="changeModelOutside()">Click me</button>

var $scope;
var app = angular.module('miniapp', []);
app.directive('wbSelect2', function () {
return {
    restrict: 'A',
    scope: {
            'selectWidth': '@',
            'ngModel': '='
    },
    link: function (scope, element, attrs) {
        //Setting default values for attribute params
        scope.selectWidth = scope.selectWidth || 200;
        element.select2({
            width: scope.selectWidth,
        });
    }
};
});



function Ctrl($scope) {
$scope.optionList = {
    'key1': 'Option 1',
        'key2': 'Option 2',
        'key3': 'Option 3',
        'key4': 'Option 4'
};

$scope.selectedOption = 'key3';
$scope.changeModelOutside = function () {
    $scope.selectedOption = 'key4';

};
}

By the way, the fix should only make changes inside the link function of directive, any fix outside the directive (I have tried using $(‘option’).select2().select2(‘val’,’1’)) will be only a work-around.

Have anyone found the same issue and have solution for this?

Upvotes: 0

Views: 2597

Answers (1)

Sergio Espallargas
Sergio Espallargas

Reputation: 211

You can take a look at this jsfiddle.

http://jsfiddle.net/zrchy7w0/6/

<div ng-app="miniapp" ng-controller="Ctrl">
    <select ng-model="selectedOption" wb-select2 ng-options="k as v for (k, v) in optionList" select-width="350px" style="width:300px"></select>
    <button ng-click="changeModelOutside()">Click me</button>
</div>

var $scope;
var app = angular.module('miniapp', []);

app.directive('wbSelect2', function () {
    return {
        restrict: 'A',
        scope: {
            'selectWidth': '@',
            'ngModel': '='
        },
        link: function (scope, element, attrs) {
            //Setting default values for attribute params
            scope.selectWidth = scope.selectWidth || 200;
            element.select2({
                width: scope.selectWidth,
            });

            scope.$watch('ngModel', function(newValue, oldValue){
                element.select2().val(newValue);
            });
        }
    };
});



function Ctrl($scope) {
    $scope.optionList = {
        'key1': 'Option 1',
            'key2': 'Option 2',
            'key3': 'Option 3',
            'key4': 'Option 4'
    };

    $scope.selectedOption = 'key3';
    $scope.changeModelOutside = function () {
        $scope.selectedOption = 'key4';
    };
}

Upvotes: 1

Related Questions