AngularJS选择的插件,选择:更新不起作用,在浏览器中工作

AngularJS chosen plugin, chosen:updated not working, works in browser

本文关键字:选择 浏览器 工作 不起作用 插件 AngularJS 更新      更新时间:2023-09-26

我已经将选定的插件集成到我的angularjs应用程序中。 我的应用程序.js看起来像这样。

myApp.directive('chosen', function() {
    var linker = function (scope, element, attr) {
        scope.$watch('countriesList', function() {
            $('#countries').trigger('chosen:updated');
            console.log('I acctuallty get in here');
        })
        element.chosen();
    };
    return {
        restrict: 'A',
        link: linker
    };
})

我的选择如下所示

<div class="control-group">
  <label for ="countries" class="control-label">Countries: </label>
  <div class="controls">
    <select chosen ng-model="countries" id="countries" ng-options="country.name for country in countriesList"  data-placeholder="Select Countries" multiple class="span chzn-select"></select>  
  </div>
</div>

问题是当页面首次加载时,选择中不显示任何内容。检查元素时,选项就在那里。

chosen:updated似乎不起作用。我把console.log()放在手表里,它正在燃烧。如果我在浏览器中运行.trigger('chosen:updated'),它可以完美运行。我确实尝试了element.trigger但也没有用。太令人沮丧了!

在调用 chosen 之前,您需要让 Angular(实际上是浏览器)正确呈现选择。您可以使用setTimeout或Angular的$timeout来执行此操作。

app.directive('chosen', function($timeout) {
  var linker = function(scope, element, attr) {
    $timeout(function () {
      element.chosen();
    }, 0, false);
  };
  return {
    restrict: 'A',
    link: linker
  };
});

第三个参数false防止不必要的摘要循环。

演示:http://plnkr.co/edit/9Afq65uatTjnb4J6ICcB?p=preview

如果您需要动态添加或删除项目,这将起作用:

app.directive('chosen', function($timeout) {
  var linker = function(scope, element, attr) {
    scope.$watch('countriesList', function() {
      $timeout(function() {
        element.trigger('chosen:updated');
      }, 0, false);
    }, true);
    $timeout(function() {
      element.chosen();
    }, 0, false);
  };
  return {
    restrict: 'A',
    link: linker
  };
});

演示:http://plnkr.co/edit/rEBu6d3HtaNhThWidB5h?p=preview

请注意,默认情况下,$watch使用引用相等性来确定是否执行侦听器。如果将项目添加到数组中,变量countriesList仍将引用同一数组,因此侦听器将不会执行。

第三个参数true传递给$watch使其使用 angular.equals 而不是引用相等性。