javascript - AngularJS 选择插件,选择 :updated not working, 在浏览器中工作

标签 javascript angularjs html jquery-chosen

我已将所选插件集成到我的 angularjs 应用程序中。我的 app.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() 放入 watch 中,它正在启动。如果我在浏览器中运行 .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 仍将引用同一个数组,因此监听器将不会执行。

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

关于javascript - AngularJS 选择插件,选择 :updated not working, 在浏览器中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28014437/

相关文章:

javascript - 在p5js中沿着弧线移动

javascript - 使用 Angular 指令有条件加载模板

javascript - 旋转图像但不旋转 Canvas

javascript - 无法打开 Dropbox 托管网站中的外部链接

javascript - 链jQ方法

javascript - 如何根据其属性值过滤充满数组的对象

javascript - ThreeJs 单击时创建对象/网格

javascript - JWT 不解码 "JWT malformed"- Node Angular

javascript - 删除 Angular 中 ng-repeat 中的所有元素

php - 每行包含 3 列的循环数据