因为项目中有需要轮播效果,所以,百度一下,发现不少案例,但是,实际用了几个,虽然可以,但是angularjs版本太低,换成新版本的angularjs就不行啦。所以,无奈,只能自己动脑动手去写了:
1、html部分
<div ng-bind-html="trustHtml"></div>2、js部分
因为要用到$sce,所以要在controller里面加上
function newIndexCtrl($scope,$rootScope,$http,$window,$cookieStore,$cookies,enums,$timeout,$element,$sce) {}
$scope.Img = ""; $http.get(enums.address + "/KnowledgeCenter/ArticleAPI/Article?keyword=&page=0&pagesize=5") .success(function (response) { $scope.Img = '<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">' + '<ol class="carousel-indicators">' + '<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>' + '<li data-target="#carousel-example-generic" data-slide-to="1" >' + '</li><li data-target="#carousel-example-generic" data-slide-to="2" ></li>' + '<li data-target="#carousel-example-generic" data-slide-to="3" ></li>' + '<li data-target="#carousel-example-generic" data-slide-to="4" ></li>' + '</ol>' + '<div class="carousel-inner" role="listBox">'; for (var i = 0; i < response.articles.length; i++) { if (i==0) { $scope.Img += '<div class="item active">' + '<img src="data:image/png;base64,' + response.articles[i].tileImage + '" style="width:100%;height:300px" >' + '<div class="carousel-caption">' + '<a href="/Home/Details?' + response.articles[i].id+ '"><small>' + response.articles[i].title + '</small> </a>'+ '</div>'+ '</div>' } else { $scope.Img += '<div class="item">' + '<img src="data:image/png;base64,' + response.articles[i].tileImage + '" style="width:100%;height:300px" >' + '<div class="carousel-caption">' + '<a href="/Home/Details?' + response.articles[i].id + '"><small>' + response.articles[i].title + '</small> </a>' + '</div>' + '</div>' } } $scope.Img+= '</div>' + '<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">' + '<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>' + '<span class="sr-only">PrevIoUs</span>' + '</a>' + '<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">' + '<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>' + '<span class="sr-only">Next</span>' + '</a>' + '</div>'; $scope.trustHtml = $sce.trustAsHtml($scope.Img); }) .error(function (data) { //console.log(data); $scope.busy = false; });
上面这一段代码是我在请求返回数据中,拼接的bootstrap中Carousel代码,然后在循环中给图片赋值。注意,在循环中有个判断,是当i=0时,添加上active。不然初次加载时,所有的图片都会显示堆叠在一起,所以,通过判断,初始加载的时候,给显示的图片添加active。另外,原点那个我是直接1、2、3、4、5直接写上去的,并没有循环赋值。此外,还有就是只有图片是在循环中写的,其他不相干的代码,都是在循环外拼接写出来。
最后拼完之后,插入并转译$scope.trustHtml = $sce.trustAsHtml($scope.Img);
前端代码也要注意别写错了。
最后效果图
如果有更好的方法,请指教。