AngularJS ngRepeat和jQuery – DOM重建问题

我非常清楚如何混合angularjs和jquery不是一个好主意。 但是,我需要一个自定义的轮播,只能通过TEXT滑动。 angularjs的所有现有旋转木马动画在很大程度上依赖于图像是内容的一部分,而我没有图像。 所以我找到了一个非常好的jquery库,用于这样的事情,称为“光滑”。

它适用于angularjs,但是当我动态地将新值添加到现有数组时,整个事情就会分崩离析。 我怎么能改变这部分代码,以便我可以动态地将对象添加到数组并保持jquery光滑的库工作?

这是代码,您可以按“上一个”和“下一个”,轮播将工作,但只要按下“添加新元素”按钮,整个事情就会崩溃。 http://jsbin.com/tihodihuho/1/edit?html,js,output

您需要确保在调用jQuery函数时unslick并且已经渲染了DOM。

你可以通过在$timeout函数中使用这些函数来实现这一点(当然,延迟为0)。 这将确保$diggest循环完成后$timeout函数内的代码将被执行。

试试这个:

 controller('myCtrl', ['$timeout',function($timeout){ var self = this; self.data = [{ id: 1, title: 'A title, representing part 1', text: 'This is my TEXT 1' }, { id: 2, title: 'Anoter interesting title that will grab your attention', text:'...and even longer text!' }]; self.next =function() { $('.your-class').slickNext(); }; self.prev =function() { $('.your-class').slickPrev(); }; self.add = function() { var newID = self.data.length + 1; self.data.push({ id:newID, title:'A totally new object!', text:'Dynamically added object to an existing array.' }); $timeout(function(){ $('.your-class').unslick(); $('.your-class').slick({ autoplay: false, autoplaySpeed: 1500, swipeToSlide: true }); }); }; }]); 

UDATE

为了解决评论中描述的OP的问题,并且它与原始问题完全无关,我提出了这个解决方法:

 $timeout(function(){ $('.your-class').unslick(); //You would think that `unslick` would take care of this, but it didn't so: $('.your-class .slick-cloned, .your-class .slick-list.draggable').remove(); //this is a workaround, which proves that the issue was with the plugin //nothing to do with the original question. In order to address this properly the //OP should open a new question or a bug in the `unslick` plugin. $('.your-class').slick({ autoplay: false, autoplaySpeed: 1500, swipeToSlide: true }); });