I am trying to make jQuery
backstretch
to work with AngularJS. I know that there is backstretch fork for AngularJS too, but now that I can't make it work with the jQuery
one, I would like to understand why. So, let's get started with the code. This is my view
<div ng-controller="main" ng-init="images=[];index=0;">
<div id="bs" ng-swipe-right="nextImage()" ng-swipe-left="prevImage()" style="position: relative;">
<div id="bslist" style="position: absolute; bottom: 10px; text-align: center;
left: 0px; right: 0px;" class="bg-stretch">
<span ng-repeat="image in images">
<a href="#" ng-class="{'active':isCurrentImageIndex($index)}"
ng-click="setCurrentImageIndex({{$index}});">{{$index}}</a></li>
</span>
</div>
</div>
</div>
(I know it's not good to have the styles here, but it is just for the test and I didn't want to embed it into my css)
The idea is that once I have entered the list of images via backstretch to #bs
I could change them by swiping left or right (which works) or by clicking from a list that the link tags make (which doesn't work). Also, the animated change that backstretch
does works. The clicking does not work, because when I click, the controller is reran and images in #bs
are reset. Correspondingly, the index will be 0 always after any click. The backend shuffles the list of images always.
And this is my controller
app.controller('main', ['$scope', '$http', function($scope, $http) {
$http({
method: 'get',
url: 'rest/bg'
}).success(function(data) {
console.log('Loaded images');
$scope.images = data.images;
$scope.index = 0;
var height = $($($('#bs').parent()).parent()).height();
$('#bs').css('height', height);
$('#bs').backstretch($scope.images, {duration: 2000, fade: 700});
$(window).on("backstretch.after", function(e, instance, index) {
$scope.$apply(function() {
console.log('running scope');
console.log(index);
$scope.index = index;
});
});
});
$scope.prevImage = function() {
$scope.index = $scope.index === 0 ? $scope.images.length - 1 : $scope.index - 1;
$('#bs').backstretch("show", $scope.index);
};
$scope.nextImage = function() {
$scope.index = $scope.index === ($scope.images.length - 1) ? 0 : $scope.index + 1;
$('#bs').backstretch("show", $scope.index);
};
$scope.isCurrentImageIndex = function(index) {
return $scope.index === index;
};
$scope.setCurrentImageIndex = function(index) {
$scope.index = index;
$('#bs').backstretch("show", $scope.index);
};
}]);