如何在AngularJS中将<select>下拉列表默认为localstorage中的值?</select>

时间:2013-08-08 05:35:35

标签: angularjs

我有一个<select>,我填充了一系列值。一切正常,我看到了预期的清单。但是现在我希望将值设置为本地存储的值(如果可用)。

我有以下代码。当我运行此代码时,标签中的类型后面的数字会更改为与localstorage中的数字相匹配,但选择框不会更改。

getContentTypeSelect: function ($scope) {
    entityService.getEntities('ContentType')
        .then(function (result) {
            $scope.option.contentTypes = result;
            $scope.option.contentTypesPlus = [{ id: 0, name: '*' }].concat(result);
            $scope.option.selectedContentType 
                 = localStorageService.get('selectedContentType');
        }, function (result) {
            alert("Error: No data returned");
        });
},

<span class="label">Type {{ option.selectedContentType }}</span>
   <select
       data-ng-disabled="!option.selectedSubject"
       data-ng-model="option.selectedContentType"
       data-ng-options="item.id as item.name for item in option.contentTypesPlus">
       <option style="display: none" value="">Select Content Type</option>
   </select>

以下是我在localstorage中设置值的代码:

    $scope.$watch('option.selectedContentType', function () {
        if ($scope.option.selectedContentType != null) {
            localStorageService.add('selectedContentType', 
                 $scope.option.selectedContentType);
            $scope.grid.data = null;
            $scope.grid.selected = false;
        }
    });

以下是存储在contentTypesPlus中的数据:

0: Object
id: 0
name: "*"
__proto__: Object
1: b
id: 1
name: "Page"
__proto__: b
2: b
id: 2
name: "Menu"
__proto__: b
3: b
id: 3
name: "Content Block"
__proto__: b

如果有一个选择框,那么如果选择框转到localstorage值?

更新

仍然希望得到答案,如果有人可以帮助我,我会很乐意接受另一个。给出的答案并不完整,我仍在等待更多信息。我希望有人可以给我一个符合我的代码的例子。感谢

2 个答案:

答案 0 :(得分:0)

我认为您需要根据select指令中定义的理解表达式确保selectedContentType必须是选项对象的id字段。

综合表达式定义为

item.id as item.name for item in option.contentTypesPlus

item.id将是ng-model option.selectedContentType

中存储的实际值

答案 1 :(得分:0)

假设这是您使用ng-model

的选择
<select 
    ng-model="language.selected" 
    ng-init="language.selected = settings.language[settings.language.selected.id]" 
    ng-options="l.label for l in settings.language" 
    ng-change="updateLanguage(language.selected)">

在您的控制器中

$scope.settings = {
enableEventsNotification: true,
enableiBeaconNotification: true,
hours: [
    { id: 0, label: '3h', value: 3 },
    { id: 1, label: '6h', value: 6 },
    { id: 2, label: '9h', value: 9 },
    { id: 3, label: '12h', value: 12 },
    { id: 4, label: '24h', value: 24 }
  ],
language: [
    { id: 0, label: 'English', value: 'en-us' },
    { id: 1, label: 'Francais', value: 'fr-fr' }
  ] 
};
$scope.hours = [];
$scope.hours.selected = $localstorage.getObject('hours',   $scope.settings.hours[1]);
$scope.settings.hours.selected = $localstorage.getObject('hours', $scope.settings.hours[1]);
$scope.hours.selected = $scope.hours.selected;