0

I'm trying to figure out how to change what option is selected in a menu, by value.

Example:

HTML

<div data-ng-app="myApp">
    <div data-ng-controller="myController">
        <p>n_images = {{n_images}}</p>
        <select data-ng-model="n_images">
            <option data-ng-selected="{{o.value == n_images}}"
                    data-ng-repeat="o in n_images_options" 
                    value="{{o.value}}">{{o.text}}</option>
        </select>
    </div>  
</div>

JavaScript

'use strict';

var myApp = angular.module('myApp', []);

myApp.controller('myController', ['$scope',
    function($scope) {
        $scope.n_images = 4;

        $scope.n_images_options = [
            {value: 1, text: "1 image"},
            {value: 2, text: "2 images"},
            {value: 3, text: "3 images"},
            {value: 4, text: "4 images"},
            {value: 5, text: "5 images"},
            {value: 6, text: "6 images"},
            {value: 7, text: "7 images"},
            {value: 8, text: "8 images"}
        ];
    }
]);

This works using AngularJS 1.1.5 (JSFiddle example).

However, it does not work in newer versions of AngularJS, such as version 1.4.6 (JSFiddle example).

How do I change what option is selected by using a value? I'm trying to create a select menu that will be initialized by a query string value from the URL.

1 Answer 1

1

For best results you need to use ng-options:

<select data-ng-model="n_images" ng-options="o.value as o.text for o in n_images_options">
</select>

https://jsfiddle.net/eywLkdub/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This worked, though I ran into another issue that I was able to solve but don't understand - when using $location.search() to get n_images from the query string and add it to the $scope so that the select menu is selecting the right option, this only worked if I used parseInt() to convert n_images to type integer (I'm assuming it was type string).
as far as I know you'll have to use` ui-router` to make it so you don't need to parseInt: github.com/angular-ui/ui-router/wiki/URL-Routing

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.