I'm using onsen ui and angular for the first time.
Basically I'm looking to navigate from the index to another page with a full screen carousel, with a specific carousel-item showing.
I started out with this code which is more or less the onsen ui sample carousel code modified to use ng-repeat and to set an initial index.
html
<ons-navigator title="Navigator" var="myNavigator">
<ons-page ng-controller="MyController">
<ons-toolbar>
<div class="center">Carousel</div>
</ons-toolbar>
<ons-carousel swipeable overscrollable auto-scroll fullscreen var="carousel">
<ons-carousel-item ng-repeat="i in ['gray', '#085078', '#373B44', '#D38312']" style="background-color: {{i}};">
<div class="item-label">{{i}}</div>
</ons-carousel-item>
<ons-carousel-cover>
<div class="cover-label">Swipe left or right</div>
</ons-carousel-cover>
</ons-carousel>
</ons-page>
</ons-navigator>
app.js
var app = ons.bootstrap();
app.controller("MyController", function($scope) {
ons.ready(function() {
carousel.setActiveCarouselItemIndex(2);
});
});
And that seemed to work fine when the carousel was the main page.
setting initial-index didn't seem to work with ng-repeat.
html
<ons-carousel swipeable overscrollable auto-scroll fullscreen initial-index="2" var="carousel">
Then, when I tried navigating to the page with the carousel, it said that carousel was undefined.
I also tried adding an event listener on the carousel, since it didn't seem to be loaded at that point.
document.addEventListener('ons-carousel:init', function() {
carousel.setActiveCarouselItemIndex(2);
});
The event listener triggered, but the setActiveCarouselItemIndex didn't seem to do anything.
This same code works when I do not use ng-repeat and have a bunch of ons-carousel-items in the html.
What I started out with: http://codepen.io/anon/pen/aObNqW
A simple example of where I am stuck: http://codepen.io/anon/pen/yNLOvY
If there is a better way to do this, I'd love to know!
Your code is fine, the problem is that you are trying to switch the carousel page when onsen is ready, which is before the carousel element is created. You can add a timeout function to make it work, or just call the script after the carousel has been loaded. If you choose the first option, just modify you controller in this way:
var app = ons.bootstrap();
app.controller("MyController", function($scope) {
ons.ready(function() {
setImmediate(function(){
carousel.setActiveCarouselItemIndex(2);
});
});
});
HERE you can find a working CodePen example