【问题标题】:Select2 event handling with Angular js使用 Angular js 处理 Select2 事件
【发布时间】:2013-09-23 20:37:28
【问题描述】:

我在使用 Angular js 触发我的 select2 on-change 事件时遇到问题。

这是我的html:

<select ui-select2="{allowClear:true}" data-placeholder="Select a Department" ng-change="DoSomething()" class="input-max" ng-model="l.DepartmentID">
    <option value=""></option>
    <option ng-repeat="d in l.LineLookups.Departments" value="{{d.DepartmentID}}">{{d.Type}}</option> </select>

When the select dropdown changes, the change event doesn't fire.这是我的控制器中的事件处理程序:

$scope.DoSomething = function () {
        alert('here');
        ...
}

处理此问题的最佳方法是什么?我被告知要注意模型值。这会奏效吗,还是有更好的方法?

【问题讨论】:

标签: angularjs


【解决方案1】:

通过观看 ng-model 来替代:

在视图中:

<select ui-select2="{allowClear:true}" data-placeholder="Select a Department" class="input-max" ng-model="l.DepartmentID">
<option value=""></option>
<option ng-repeat="d in l.LineLookups.Departments" value="{{d.DepartmentID}}">{{d.Type}}</option>
</select>

在控制器中:

$scope.$watch('l.DepartmentID', function (newVal, oldVal) {
    if (oldVal == newVal) return;
    alert('here');
}, true);

【讨论】:

  • 这被调用了多次,我看到了多个警报。
【解决方案2】:

您可以向 angular-ui 库添加一个 jquery 侦听器,然后它会触发一个 angular 事件 - 如下所示:

  // Set initial value - I'm not sure about this but it seems to need to be there
  elm.select2('data', controller.$modelValue);
  elm.on('change', function() {
      scope.$emit('select2:change', elm);
  });

然后在控制器中注册一个角度事件监听器:

    $scope.$on('select2:change', function (event, element) {
        console.log('change fired by' + element.get(0).id);
    });

【讨论】:

    【解决方案3】:

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

    标记

    <select 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 2013-07-19
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多