AngularJS + select2 - 如何设置初始值

时间:2016-10-30 11:36:39

标签: javascript html angularjs select2

我想在我的AngularJS项目中使用Select2,所以我添加了这样的输入:

<select class="find-neighborhood js-states form-control" 
    ng-model="regionIdentifier" 
    ng-init="">
 </select>

幸运的是,每当regionIdentifier发生变化时,我都会发现。实际上我想在Select2中设置初始值。这是我的javascript代码:

$(".find-neighborhood").select2({
    dir: "rtl",
    placeholder: "find neighborhood ...",
    allowClear: true,
    data: $scope.regions
 }); 

我的$scope.regions看起来像是:

[object,object,object]

每个对象都像:

0 :Object
 id:52623
 regionSlug:yvuj
 text:yvuj1

如何在select2中初始化值?

1 个答案:

答案 0 :(得分:0)

你应该创建一个指令,使这个工作全局和好。这是一个简单的示例,可让您初始化select2将默认选项值设置为您的选择。您可以在plnkr找到有效的版本。虽然select2依赖于jQuery,但您可能会寻找另一个lib来使其工作。一些开发人员不愿意在AngularJS项目中包含jQuery。

控制器

//option list 
$scope.regions = {
    'test1' : {
        id: 1
    },
    'test2' : {
        id: 2
    },
    'test3' : {
        id: 3
    },
    'test4' : {
        id: 4
    },
    'test5' : {
        id: 5
    }
};

//model & selected value setup
$scope.regionIdentifier = 3;

视图

<select class="js-example-basic-single"
        ng-model="regionIdentifier"
        items="regions"
        items-selected="regionIdentifier"
        id="regionSelection"
        select-two>
</select>

指令

/**
 * Simple select2 directive
 */
angular.module('app').directive('selectTwo', ['$timeout', function($timeout){

    return {
        restrict : 'EA',
        transclude : true,
        terminal: true,
        templateUrl : 'views/directive/select2.html',
        scope: {
            items: "=",
            itemsSelected: "="
        },
        link: function($scope, $element, $attrs, $controller){

            //format options https://select2.github.io/select2/#documentation
            function format(state) {

                //init default state
                var optionTemplate = state.text;
                if (!state.id || state.id == 0) { //option group or no selection item
                    return optionTemplate;
                }

                return optionTemplate;
            }

            //init on load
            $timeout(function(){

                //if multiple options are possible, parse an comma seperated list into itemsSelected like 1,2,5,23,21
                if (angular.isString($scope.itemsSelected) && $scope.itemsSelected.split(',').length > 1) {
                    $scope.itemsSelected = $scope.itemsSelected.split(',');
                }

                $($element[0]).select2({
                    formatResult: format,
                    formatSelection: format,
                    escapeMarkup: function(m) { return m; }
                }).val($scope.itemsSelected == undefined ? [0]: [$scope.itemsSelected]).trigger("change");
            });
        }
    };
}]);

指令模板views/directive/select2.html

<option ng-repeat="(name, item) in items track by $index"
    value="{{ item.id }}">
    {{ name }}
</option>