Samantha J T Star
Samantha J T Star

Reputation: 32818

How can I set the initial value of a <select> with AngularJS?

I am using this code in my controller:

$scope.$watch('option.selectedPageType', function () {
    if ($scope.isNumber($scope.option.selectedPageType)) {
        localStorageService.add('selectedPageType', $scope.option.selectedPageType);
    }
})

getPageTypes: function ($scope) {
            $scope.option.pageTypes = [
                { id: 0, type: 'Edit Basic' },
                { id: 1, type: 'Edit Standard' },
                { id: 2, type: 'Report' }
            ];
            $scope.option.selectedPageType = parseInt(localStorageService.get('selectedPageType'));
},

and in my HTML:

<select data-ng-model="option.selectedPageType"
        data-ng-options="item.id as item.type for item in option.pageTypes">
        <option style="display: none" value="">Select Page Type</option>
</select>

Instead of using the "Select Page Type" option. How can I make it so my code defaults to the value in local storage or if there is nothing there then to one of the values I have in my option.pageTypes list ?

Upvotes: 1

Views: 407

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Have your localStorageService return null if there is nothing stored. If it does exist, have the service return the integer

Then in controller:

/* assume want first item in array */
$scope.option.selectedPageType = localStorageService.get('selectedPageType') || $scope.option.pageTypes[0].id

Upvotes: 1

Alejandro Urbano Alvarez
Alejandro Urbano Alvarez

Reputation: 3346

Try using ng-init on the <select ...>:

<select data-ng-model="option.selectedPageType"
    data-ng-options="item.id as item.type for item in option.pageTypes"
    data-ng-init="option.selectedPageType=DEFAULT_VALUE">

See this fiddle: http://jsfiddle.net/CaeUs/5/

Upvotes: 1

Related Questions