0

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);
});

用户实际上在这里所做的是编辑标记到他/她的地址的标签,并且通过编辑我的意思是用户可以将新标签标记到他/她的地址或删除以前标记的标签。这就是为什么我需要跟踪添加了哪些标签以及删除了哪些标签。

更新

我在这个讨论中看到了一个合理的解决方案,但我无法让提供的代码与我的一起工作,所以我做了一些解决方法,这就是我所做的。

所以不要添加,

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);
}

并且工作得很好。

但我怀疑这是一个非常好的主意,我仍然希望有更好的解决方案。

4

1 回答 1

0

我使用指令来封装选择,然后在链接函数中我只检索选择元素并在事件处理程序处。

标记:

<select name="id" data-ng-model="tagsSelection" ui-select2="select2Options">
    <option value="{{user.id}}" data-ng-repeat="user in users">{{user.name}}</option>
</select>

Javascript:

link: function (scope, element, attributes) {
    var select = element.find('select')[0];
    $(select).on("change", function(evt) {
        if (evt.added) {
            // Do something
        } else if (evt.removed) {
            // Do something.
        }
    });

    $scope.select2Options = {
        multiple: true
    }
}
于 2014-09-09T19:49:17.743 回答