如果我们开发人员自己原生手写,将会花费很多的时间,最终得不偿失。
接下来就详细说说如何使用angular-ui发热图片轮播模块,并且将它写成一个指令(便于复用)
一如既往的我们项目中使用时requireJS进行js代码的编译
准备工作:
1):引入angularJS,ui-bootstrap-tpls-1.3.2(我使用的是1.3.2版本的)
第一步:自己写一个指令(命名为picchange)
说明:指令控制器中的代码都是angualr-ui官网上拷贝的(因为此文章的重点是如何将其封装成指令,其他的不做重点)
指令的js代码
显示的图片(0:下标为0的图片)
var slides = $scope.slides = [];//用于存放图片地址
var currIndex = 0;
$scope.addSlide = function() {
var newWidth = slides.length + 1;
slides.push({
image: $scope.picurl[newWidth].imgUrl,//图片的url
text: $scope.picurl[newWidth].wordDes,//图片的描述文字
id: currIndex++
});
};
//................随机...........
$scope.randomize = function() {
var indexes = generateIndexesArray();
assignNewIndexesToSlides(indexes);
};
for (var i = 0;i<$scope.picurl.length;i++) {
$scope.addSlide();
}
// Randomize logic below
function assignNewIndexesToSlides(indexes) {
for (var i = 0,l = slides.length; i < l; i++) {
slides[i].id = indexes.pop();
}
}
function generateIndexesArray() {
var indexes = [];
for (var i = 0; i < currIndex; ++i) {
indexes[i] = i;
}
return shuffle(indexes);
}
// http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
var tmp,current,top = array.length;
if (top) {
while (--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
}
return array;
}
}],templateUrl:'js/directives/picchange/picchange.html',//轮播的页面
link:function(s,e,attrs){
},}
}]);
});
好了上面的代码都是拷贝来的,不做解释
轮播模块的html:(picchange.html),指令的html(这个没啥理解的)
指令的html
<div style="height: 305px;">
<uib-carousel no-wrap="noWrapSlides" interval="myInterval" active="active">
<uib-slide index="slide.id" ng-repeat="slide in slides track by slide.id">
<img style="margin: auto;" ng-src="{{slide.image}}">
<div class="carousel-caption">
<h4>Slide {{slide.id}}</h4>
<p>{{slide.text}}</p>
</div>
</uib-slide>
</uib-carousel>
<div class="row">
<div class="col-md-6">
<button class="btn btn-info" type="button" ng-click="addSlide()">Add Slide</button>
<button class="btn btn-info" type="button" ng-click="randomize()">Randomize slides</button>
<div class="check<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>">
<label>
<input type="check<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>" ng-model="noWrapSlides">
Disable Slide Looping
</label>
</div>
</div>
<div class="col-md-6">
Interval,in milliseconds: <input class="form-control" type="number" ng-model="myInterval">
<br>Enter a negative number or 0 to stop the interval.
</div>