0

I've got a simple page selector I'm using in an Angular 1.5 page. The select works for the most part, but the ng-selected part does not.

If I'm on page 3, (which is ironically the last page, not sure if that matters) 3 is selected by default. If I'm on page 1 or 2, the first item (blank) is selected. I'm not super versed in Javascript, but figured it might be a type issue. Tried settings $scope.thisPage with parseInt(page) and page.toString() just in case it did something under the sheets I wasn't aware of, but it all turned out the same.

app.controller('myCtrl', ['$scope','$route','$routeParams', function($scope,$route,$routeParams) {
    $scope.pages = [];
    var page = $routeParams.p ? $routeParams.p : 1
    $scope.thisPage = page; 
    for (var i = 0; i < 5; i++) {
        $scope.pages.push(i);
    }
}]);

<form name="myForm">
    <select ng-model="selectedPage" ng-change="switchPage(selectedPage)">
    <option ng-repeat="p in pages" ng-value="{{p}}" ng-selected="{{p == thisPage}}">{{p}}</option>
    </select>
</form>

2 Answers 2

1

You need no set selected property

<form name="myForm">
    <select ng-model="selectedPage" ng-change="switchPage(selectedPage)">
    <option ng-repeat="p in pages" ng-value="{{p}}">{{p}}</option>
    </select>
</form>

Instead bind the selectedPage value with thisPage

app.controller('myCtrl', ['$scope','$route','$routeParams', function($scope,$route,$routeParams) {
    $scope.pages = [];
    var page = $routeParams.p ? $routeParams.p : 1
    $scope.selectedPage= page; ////////////////////////////////
    for (var i = 0; i < 5; i++) {
        $scope.pages.push(i);
    }
}]);
Sign up to request clarification or add additional context in comments.

4 Comments

What if he has a reason to use ng-selected ? However, that's correct too :)
why to use ngSelected when you are having two way data binding
If there is no point on stocking the value and it's only used for display with proper styling ? Who are we to judge :D
Thanks so much -- this worked. I could have sworn I tried this earlier (I tried a few solutions, but most were for fancier models). Anywho, on to the next problem. :)
1

ngSelected require an expression as following p == thisPage and not {{p == thisPage}}

Source : https://docs.angularjs.org/api/ng/directive/ngSelected

2 Comments

this gives me the same results. :(
@kiss-o-matic oh... Could you create a plunker or codepen with your project ? It helps debugging :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.