发生这种情况的原因是因为插件本身极大地修改了由ngRepeat 生成的 html,导致 angular 无法更新转发器,因为它不再能够识别结构。
为了防止 angular 在更新中继器时混淆,您可以:
我在这里有一个工作示例:
http://plnkr.co/edit/ZQrDZ3Nr33S95Y4uy1AZ?p=preview
它通过添加 slickApply 方法对 angular-slick.js 包装器稍作修改,以便您可以在控制器中轻松完成此操作。
变化:
angular-slick.js
touchThreshold: '@',
vertical: '@',
slickApply: '=' // this is the two way binding that changes the interface
},
link: function (scope, element, attrs) {
var initializeSlick, isInitialized;
var slider; // slider has been moved from the initializeSlick function to here
/*
This function takes another function as an argument
and will reset the slick plugin, call the function, and reload it
*/
scope.slickApply = function(apply){
if (isInitialized) {
slider.unslick();
}
apply();
initializeSlick();
}
initializeSlick = function () {
return $timeout(function () {
var currentIndex;
slider = $(element);
index.html
这里唯一改变的是添加了slick-apply 属性,它引用了$scope 中的slickApply 函数
<h1>Hello Plunker!</h1>
<slick init-onload="false" slick-apply='slickApply' data="dataLoaded" slides-to-show="3" dots="true">
<div ng-repeat="item in items">
<span>
script.js
这里唯一改变的是将$scope.items 的赋值封装到$scope.slickApply 函数中。
$scope.messItUp = function(){
$scope.slickApply(function(){
$scope.items = [
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 1'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 2'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 3'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 4'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 5'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 6'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 7'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 8'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 9'},
{imgSrc: 'http://lorempixel.com/325/325/sports/', label: 'label 10'}
]
});
}
您也可以在不修改包装器的情况下完成所有这些操作,但这需要您在控制器中执行笨拙的 jQuery / angular 操作,正如 miron 所示:
http://plnkr.co/edit/WCEWwgNcIEC0rseaZIO6?p=preview
我认为您绝对可以改进前一个示例,特别是通过修改包装器,使其能够识别角度集合,目前它不这样做。但这显然比我在这里提供的热修复要多得多。
如果您打算在整个代码中更多地使用这个 slick 库,我绝对建议您 fork git 存储库,以便您可以以更易于管理的方式对其进行任何其他更改。
但是,由于整个 包装器 实际上是 1 个文件,其中甚至没有 100 行代码,我认为直接在您的代码库中采用它并没有任何问题。
但是,如果您想合并上游更改,我建议将其保留为咖啡脚本。但是编译后的输出看起来并不可怕,所以我猜它并不重要。