2013-12-16 29 views
5

給定一個jQuery插件,在由ng-repeat呈現的元素列表上初始化它的最簡潔方法是什麼?jQuery插件和角度重複

例如,我想列出可拖動的單詞。在控制器我把名單從API:

$scope.words = Words.get(...) 

並在視圖我重複他們:

<article ng-controller="WordsCtrl"> 
    <div class="word" ng-repeat="word in words"> 
     {{word}} 
    </div> 
</article> 

而剩下的就是運行插件初始化代碼,就像:

$(elem).children('.word').draggable() 

但是這需要在範圍內的每次更改後運行。這個去哪了?

+0

http://codef0rmer.github.io/angular-dragdrop/#/ –

+0

https://github.com/angular-ui/ui-sortable –

回答

1

如果你使用jQuery,您可以創建一個簡單jqDraggable指令,將調用.draggable()

app.directive('jqDraggable', function() { 
    return { 
     restrict: 'A', 
     link: function (scope, elm, attr) { 
      elm.draggable(); 
     } 
    };  
}); 

那麼您需要做的:

<article ng-controller="WordsCtrl"> 
    <div jq-draggable="true" class="word" ng-repeat="word in words"> 
     {{word}} 
    </div> 
</article> 

這也應該工作的$scope.words更改時。

這裏是一個示例plunker:
http://plnkr.co/edit/ywWifeNPcTFYTYFMI2Of?p=preview

+0

如果我知道它的正確性,這裏的解決方案是將該指令放在'ng - 重複「,而不是像我一樣對孩子們進行嘗試,非常優雅。 – danza

0

要做到這一點的最佳方法是在放置重複項目的父元素上創建指令。然後創建一個$ watch表達式來監視ng-repeat的範圍,如果它發生變化,則在其子節點上應用.draggable。

這裏的一個插件已經做了你

http://codef0rmer.github.io/angular-dragdrop/#/

回答你的問題對觀看範圍雖然這裏有一個roughe例如:

你的元素看起來像:

<div draggable="items"> 
    <div ng-repeat="item in items"></div> 
</div> 

app.directive('draggable',function(){ 
return { 
    restrict: 'A', 
    link: function($scope,$elem,$attrs){ 
     $scope.$watch($attrs.draggable,function(nv,ov) { 
     //the scope of repeat has changed do something here 
     } 
    } 
} 
}); 

所以它會坐在那裏看物品,當它變化時你可以應用拖動

+0

什麼是「draggable =」items「'和'$ attrs.draggable'是必要的嗎?另外,我應該運行'nv.forEach(function(e){$(e).draggable();}'? – danza