我一直试图用AngularJS(1.2.4)实现Selectize。我使用this directive与插件进行交互,一切都运行顺利到现在为止。当使用普通选择框中的ngModel它工作正常,并返回预期的对象但是当我尝试将它与多个属性一起使用时,它不会设置模型。
我已经检查了DOM并且看起来脚本从隐藏的选择中删除了未选择的选项,这可能会影响角度绑定。
我创建了一个Plunkr来演示这种行为。
http://plnkr.co/It6C2EPFHTMWOifoYEYA
由于
答案 0 :(得分:3)
正如上面的评论所述,您的指令必须听取选择插件中的更改,然后通过ng-model
通知角度。
首先,您的指令需要使用以下内容来请求ngModel
控制器的可选引用:
require: '?ngModel'
。
它作为第4个位置的参数注入到链接函数中:
function(scope,element,attrs,ngModel){}
然后,你必须听取选择中的变化
$(element).selectize().on('change',callback)
并通过ngModel.$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);
});
});
});
}
};
});
此外: