Bishoy Bisahi
Bishoy Bisahi

Reputation: 377

Bind from ngstorage to dropdown

I used ngstorage to save some value in localstorage My contrroller is:

app.controller("main", function( $scope, $localStorage) {
 $scope.$storage = $localStorage.$default({           
            selectedlanguage: { language: null, text: "All Languages" }
        });
  $scope.languages = [
            { language: null, text: "All Languages" },
            { language: "en", text: "English" },
            { language: "ar", text: "Arabic" }
        ];

}

My view is:

<select ng-model="$storage.selectedlanguage" ng-options="lang.text for lang in languages">
 </select>

when reload the page angular can not bind the selectedlanguage Thanks in advance

Upvotes: 0

Views: 171

Answers (1)

Shannon Hochkins
Shannon Hochkins

Reputation: 12186

In the ng-options attribute, you can specify the values and title for each option in the expression it self, your other issue was that you're specifying an object as the ng-model, you need to tell the dropdown which value to match on, so accessing language on the selectedlanguage object will work fine.

<select ng-model="$storage.selectedlanguage.language" ng-options="lang.language as lang.text for lang in languages">
</select>

The above is the same as below, but a more complex expression, the below is just easier to read but it's exactly the same:

<select ng-model="$storage.selectedlanguage.language">
    <option ng-repeat="lang in languages" value="{{lang.language}}">
      {{lang.text}}
    </option>
</select>

Demo: https://jsfiddle.net/suunyz3e/289/

Upvotes: 1

Related Questions