【发布时间】:2014-08-18 04:00:57
【问题描述】:
select2 提供了一些自定义事件,我希望能够收听它们,特别是“select2-removed”或更好的是它的自定义“更改”事件,我一直在互联网上搜索一些例子,但没有运气。
这是我到目前为止所做的:
HTML:
<input type="hidden" class="form-control" id="tags" ui-select2="modal.tags" data-placeholder="Available Tags" ng-model="form.tags">
JavaScript(角度)
$scope.form = {tags: []};
postalTags = [
{
id: 1,
text: 'Permanent Address'
},
{
id: 2,
text: 'Present Address'
}
];
$scope.modal {
tags: {
'data': postalTags,
'multiple': true
}
};
// I doubt this is going to work, since i think this is only going to
// listen on events emitted by $emit and $broadcast.
$scope.$on('select2-removed', function(event) {
console.log(event);
});
// I can do this, but then i will not know which was removed and added
$scope.$watch('form.tags', function(data) {
console.log(data);
});
用户实际上在这里所做的是编辑标记到他/她的地址的标签,并且通过编辑我的意思是用户可以将新标签标记到他/她的地址或删除以前标记的标签。这就是为什么我需要跟踪添加了哪些标签以及删除了哪些标签。
更新
我在 discussion 上看到了一个合理的解决方案,但我无法使提供的代码与我的代码一起使用,所以我做了一些解决方法,这就是我所做的。
所以不要添加,
scope.$emit('select2:change', a);
这里的某个地方,
elm.select2(opts);
// Set initial value - I'm not sure about this but it seems to need to be there
elm.val(controller.$viewValue)
我把它放在这里,
if (!isSelect) {
// Set the view and model value and update the angular template manually for the ajax/multiple select2.
elm.bind("change", function (e) {
// custom added.
scope.$emit('select2:change', e);
e.stopImmediatePropagation();
然后我在我的控制器上做了通常的操作,
$scope.$on('select2:change', function(event, element) {
if(element.added) console.log(element.added);
if(element.removed) console.log(element.removed);
}
并且工作得很好。
但我怀疑这是个好主意,我仍然希望有更好的解决方案。
【问题讨论】:
-
其他讨论发生在这里:stackoverflow.com/questions/15622522
-
@apairet 是的,已经看到了这两个,第一个确实很有帮助,但它涉及我修改第三方代码,就最佳实践而言,这并不是一个好主意。我希望有另一种方式。但目前这就是我为解决我的问题所做的,虽然只是有点不同,但我无法让第一个线程上的给定代码工作,所以我尝试了不同的方法,我想我必须用合理的解决方案更新我的问题。因为我仍然希望有更好的解决方案。
标签: angularjs jquery-select2 ui-select2 angularjs-select2