Angular ng-repeat和jQuery插件

时间:2013-09-11 09:11:22

标签: jquery angularjs angularjs-directive angularjs-ng-repeat

我正在尝试将this jQuery plugin转换为Angular指令。我做了以下事情:

define(['directives/directives'], function(directives){
directives.directive('vivifysortable', ['$rootScope', function ($rootScope){
    return {
        controller: function ($scope, $element, $attrs){
            // here i pasted definition of multiselectable, 
            //and multisortable from the above jsfiddle
        },
        link: function($scope, $element, $attrs) {
            if ($scope.$last === true) {                    
                setTimeout(function() {
                        angular.element($element).multisortable({                            
                        connectWith: ".product-backlog-column",
                        selectedClass: "ui-selected"
                    });
                })
            }
         }   
    }
}]); 
});

如果我有类似的东西,这可以正常工作

 <ul class="product-backlog-column" vivifysortable >
    // some hardcoded values for testing purposes
    <li> test  1 </li>
    <li> test  2 </li>
    <li> test  3 </li>
 </ul>

但是如果我使用ng-repeat,看起来它根本不起作用

<ul class="product-backlog-column" vivifysortable >
    <li ng-repeat='item in items'>
        {{item.title}}
    </li>
</ul>

看起来,ng-repeat`给了我很多困难,但我不知道为什么,以及如何解决它。

这里是jsfiddle(我不确定我是否通过将Angular onLoad和jQuery包含为外部资源来正确创建它)。

1 个答案:

答案 0 :(得分:3)

我通过添加$timeout解决了这个问题。重构代码如下所示:

 link: function($scope, $element, $attrs) {
            $timeout(function () {
                angular.element($element).multisortable({

                    connectWith: ".product-backlog-column",
                    selectedClass: "ui-selected"
                });
            }, 0);

  }   

问题是$timeout将停止执行指令,直到ng-repeat完成渲染。那是我初学者的解释。如果有经验的人可以对此有所了解,请做。

相关问题