【问题标题】:AngularJS: Issues integrating a directive using ng-repeat with an external pluginAngularJS:使用 ng-repeat 将指令与外部插件集成的问题
【发布时间】:2013-08-22 05:55:37
【问题描述】:

我想构建一个指令,它将下拉(选择)链接到外部 jquery 插件。

这是我的 templateUrl 视图的指令代码:

<select multiple="multiple">
  <option data-ng-repeat="(key,label in opts)"
     value="{{key}}">{{label}}</option>
</select>

这是我的指令的链接功能:

link: function(scope, element, attrs)
   {
       console.log( scope.opts );
       console.log( $(element).html() );
       $(element).chosen(); //call external plugin
   }

这里的问题是,由于某种原因,当调用 link 函数时,选择尚未使用 ng-repeat 填充选项。因此,当我调用 jquery 插件时,它会显示一个空下拉列表,即使稍后选择填充了选项。

console.log( scope.opts ); 的输出正确显示了带有选项的对象,而console.log( $(element).html() ); 仅显示:

&lt;!-- ngRepeat: (key,label) in opts --&gt;

有没有办法在 ng-repeat 填充选择时收到通知,所以我只能调用外部插件?

【问题讨论】:

  • Angular 没有任何机制来可靠地检测 DOM 何时呈现。你最好的选择是使用$timeout。说了这么多,你为什么不看choosen指令,我在这里找到了github.com/localytics/angular-chosen
  • @Chandermani 谢谢,但我想自己写。无论哪种情况,来自linkscope.opts 变量上的$scope.$watch 似乎都可以工作,如果我从$scope.$watch 中调用$(element).chosen(),它似乎工作正常

标签: javascript jquery angularjs


【解决方案1】:

这个问题的解决方案(不知道 dom 何时被 angularJS 更新)是使用$timeout。然而,通过下拉菜单,ngOptions 很难与外部插件集成。因此,我建议任何想要将所选插件或任何其他插件与下拉菜单集成的其他人,只需使用 ngRepeatngSelected 使用普通 &lt;option&gt;s 而不是 ngOptions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多