在AngularJS选项卡式视图中设置默认的radio / input / checkbox值

时间:2014-08-05 14:09:41

标签: javascript angularjs ionic-framework

我有一个使用Ionic Framework的AngularJS应用程序,它有一个带有“设置”选项卡的选项卡视图,该选项卡将存储用户选项。我想在应用程序最初启动时使用这些设置,而我可以在localStorage中使用存储的值,我希望能够检查设置选项卡上设置的选项。

现在,如果你加载设置选项卡,你会看到其中一个单选按钮在你加载时从关闭到开启,这就是每当我设置一个默认值时会发生什么。如何在应用程序启动时设置此设置,而不是在打开选项卡本身时设置?

这就是我的controllers.js的样子:

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope, $window, $ionicPlatform) {

    $ionicPlatform.ready(function() {
        if ( ! $window.localStorage.getItem( 'grossoption' ) ) {
        $window.localStorage.setItem( 'grossoption', 'year' );
    }

    if ( ! $window.localStorage.getItem( 'resultoption' ) ) {
        $window.localStorage.setItem( 'resultoption', 'month' );
    }
    });

    $scope.grossOptionsList = [
    { text: "Year", value: "year" },
    { text: "Month", value: "month" },
    { text: "Week", value: "week" },
    { text: "Day", value: "day" }
    ];

    $scope.resultsOptionsList = [
    { text: "Year", value: "year" },
    { text: "Month", value: "month" },
    { text: "Week", value: "week" },
    { text: "Day", value: "day" }
    ];

// Default values
    $scope.data = {};
    $scope.data.grossOptions = 'year';
    $scope.data.resultOptions = 'month';


    $scope.updateGrossOptions = function(item) {
      $window.localStorage.setItem( 'grossoption', item.value );
        console.log( 'Gross option: ' + item.value );
    }

    $scope.updateResultOptions = function(item) {
      $window.localStorage.setItem( 'resultoption', item.value );
        console.log( 'Results option: ' + item.value );
    }

})

.controller('SettingsCtrl', function($scope, $window, $ionicPlatform) {
$ionicPlatform.ready(function() {


    if ( ! $window.localStorage.getItem( 'toggle1' ) ) {
        $window.localStorage.setItem( 'toggle1', 'true' );
    }

    if ( ! $window.localStorage.getItem( 'toggle2' ) ) {
        $window.localStorage.setItem( 'toggle2', 'false' );
    }


});

$scope.data = {};
$scope.data.toggle1 = $window.localStorage.getItem( 'toggle1' ) === "true";
$scope.data.toggle2 = $window.localStorage.getItem( 'toggle2' ) === "true";

$scope.update_toggle1 = function() {
    $window.localStorage.setItem( 'toggle1', $scope.data.toggle1 );
    console.log( 'Toggle 1: ' + $scope.data.toggle1 );
}

$scope.update_toggle2 = function() {
    $window.localStorage.setItem( 'toggle2', $scope.data.toggle2 );
    console.log( 'Toggle 2: ' + $scope.data.toggle2 );
}

}) 我已设置an example plnkr here,其中显示了我的应用在加载“设置”标签时当前所具有的行为。

感谢有关如何以最佳方式处理Angular的任何反馈。

1 个答案:

答案 0 :(得分:1)

您可以在“ng-checked”中使用“if”条件,如下所示:

<ion-toggle ng-checked="(myVar== 1)?true:false;" ng-change="myFunc(myVar)" ng-model="myVar" toggle-class="toggle-calm">{{myVar}}</ion-toggle>