如何使用AngularJS设置的初始值?

时间:2023-01-06 19:37:04

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:

在我的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 ?

而不是使用“选择页面类型”选项。我怎么能这样做,所以我的代码默认为本地存储中的值,或者如果那里没有任何内容,那么我的option.pageTypes列表中的值之一?

2 个解决方案

#1


1  

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

如果没有存储任何内容,请让localStorageService返回null。如果确实存在,请让服务返回整数

Then in controller:

然后在控制器中:

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

#2


1  

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/

看到这个小提琴:http://jsfiddle.net/CaeUs/5/

#1


1  

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

如果没有存储任何内容,请让localStorageService返回null。如果确实存在,请让服务返回整数

Then in controller:

然后在控制器中:

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

#2


1  

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/

看到这个小提琴:http://jsfiddle.net/CaeUs/5/