Selectize&AngularJS不与选择框一起玩(多个选项)

Dan*_*res 5 angularjs selectize.js

我一直试图用AngularJS(1.2.4)实现Selectize.我正在使用这个指令与插件接口,一切都运行顺利到现在为止.当从正常选择框使用ngModel它工作正常,并返回预期的对象但是当我尝试使用它与multiple属性时,它不会设置模型.

我已经检查了DOM并且看起来脚本从隐藏的选择中删除了未选择的选项,这可能会使角度绑定变得混乱.

我创建了一个Plunkr来演示这种行为.

http://plnkr.co/It6C2EPFHTMWOifoYEYA

谢谢

Jon*_*son 3

正如上面的评论中提到的,您的指令必须侦听 selectize 插件中的更改,然后通过 通知 Angular 发生了什么ng-model

首先,您的指令需要请求对ngModel控制器的可选引用,其中包含以下内容:

require: '?ngModel'

它作为参数注入到链接函数的第四个位置:

function(scope,element,attrs,ngModel){}
Run Code Online (Sandbox Code Playgroud)

然后,您必须监听 selectize 的变化 $(element).selectize().on('change',callback)

并通知 ngModelngModel.$setViewValue(value)

这是您的指令的修改版本。它应该让你开始。

angular.module('angular-selectize').directive('selectize', function($timeout) {
    return {
        // Restrict it to be an attribute in this case
        restrict: 'A',
        // optionally hook-in to ngModel's API 
        require: '?ngModel',
        // responsible for registering DOM listeners as well as updating the DOM
        link: function(scope, element, attrs, ngModel) {
            var $element;
            $timeout(function() {
                $element = $(element).selectize(scope.$eval(attrs.selectize));
                if(!ngModel){ return; }//below this we interact with ngModel's controller
                //update ngModel when selectize changes
                $(element).selectize().on('change',function(){
                    scope.$apply(function(){
                        var newValue = $(element).selectize().val();
                        console.log('change:',newValue);                    
                        ngModel.$setViewValue(newValue);
                    });
                });
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

还: