Search code examples
javascriptangularjsng-optionsangularjs-ng-init

Set selected value of select menus


I have three select menu that bind to each other and want to set selected value of two select menus. Value that I want to set comes with scope. I try ng-init but that didn't work. Working Plunker

<select ng-init="selManga=direk" ng-model="selManga" ng-options="manga.seri for manga in mangas">
    <option value="">Select a Manga</option>
</select>

<select ng-init="selChapter=bacanak" ng-show="selManga" class="browser-default" ng-model="selChapter" ng-options="+idx as chapter.klasor for (idx, chapter) in selManga.randomword">
    <option value="">Chapter</option>
</select>

<select ng-show="selManga.randomword[selChapter].yol" class="browser-default" ng-model="selPage" ng-options="+idx as (+idx + 1) for (idx, page) in selManga.randomword[selChapter].yol">
    <option value="">Page</option>
</select> 

Javascript:

.controller('nbgCtrl',function  ($scope, MMG, $stateParams) {
$scope.direk = $stateParams.seri;
$scope.bacanak = $stateParams.klasor;

MMG.adlar.success(function(loHemen) {
    $scope.mangas = loHemen;
});
$scope.next = function (manga, chapter, page) {
    var nextPage = page + 1;
    if (angular.isDefined(manga.randomword[chapter].yol[nextPage])) {
        $scope.selPage = nextPage;
    } else if (angular.isDefined(manga.randomword[chapter + 1])) {
        $scope.selChapter = chapter + 1;
        $scope.selPage = 0;
    }
}
})

Solution

  • To extract the values for the manga,chapter and page from the url you should use the $routeParams object, which your module should include ngRoute.

    I've prepared an example here it might not be obvious but if you download the code and run it in your own browser you can access routes like Manga/Naruto/ch/100 from the url bar.

    Once you've restructured your application to use routes and routeParams, in my example I directly bind the chapter and page I get from the url to the view but if you bind them to the models of your dropdowns the dropdowns will update.

    $scope.params = $routeParams;
    $scope.selManga = $scope.params.bookId
    

    This does not update the url as you select from the dropdown.