【问题标题】:Get and set a checkbox in Ionic Framework (AngularJS)在 Ionic Framework (AngularJS) 中获取和设置复选框
【发布时间】:2015-07-04 14:06:59
【问题描述】:

我需要跟踪用户何时更改 Ionic 中复选框的状态,将其保存到 localStorage,然后使用它稍后再次加载 - 所以它会记住他们的设置。

我的切换代码如下所示:

<li class="item item-toggle">
     National Insurance {{ni_toggle}}
     <label class="toggle toggle-positive">
       <input type="checkbox" ng-model="ni_toggle" ng-click="updateLocalStorage()" id="has_national_insurance" name="has_national_insurance">
       <div class="track">
         <div class="handle"></div>
       </div>
     </label>
  </li>

在我的控制器中,我有:

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

.controller('SettingsCtrl', function($scope, $ionicPlatform) {
    $ionicPlatform.ready(function() {
    // Ready functions

    });

 $scope.updateLocalStorage = function() {

    window.localStorage.setItem( 'has_national_insurance', $scope.ni_toggle );
    console.log( $scope.ni_toggle );

}

})

但是,它以undefined 的身份注销到控制台。如果我明确设置$scope.ni_toggle = false;,它将记录为 false,并且在我将复选框切换为 on 时不会更新为 true。

编辑:

app.js:

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

  .run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if(window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if(window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }

    });
  })



.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

    // setup an abstract state for the tabs directive
    .state('tab', {
      url: "/tab",
      abstract: true,
      templateUrl: "templates/tabs.html"
    })

    // Each tab has its own nav history stack:

    .state('tab.dash', {
      url: '/dash',
      views: {
        'tab-dash': {
          templateUrl: 'templates/tab-dash.html',
          controller: 'DashCtrl'
        }
      }
    })

    .state('tab.settings', {
      url: '/settings',
      views: {
        'tab-settings': {
          templateUrl: 'templates/tab-settings.html',
          controller: 'SettingsCtrl'
        }
      }
    })

    .state('tab.info', {
      url: '/info',
      views: {
        'tab-info': {
          templateUrl: 'templates/tab-info.html',
          controller: 'InfoCtrl'
        }
      }
    })

        .state('tab.about', {
      url: '/about',
      views: {
        'tab-about': {
          templateUrl: 'templates/tab-about.html',
          controller: 'AboutCtrl'
        }
      }
    })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/dash');

});

controllers.js:

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

.controller('DashCtrl', function($scope) {
})

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

    });

    $scope.ni_toggle = $window.localStorage.getItem('has_national_insurance') === "true";

    $scope.updateLocalStorage = function() {
            $window.localStorage.setItem( 'has_national_insurance', $scope.ni_toggle );
            console.log( $scope.ni_toggle );
        }   


})

.controller('InfoCtrl', function($scope) {
})

.controller('AboutCtrl', function($scope) {
});

模板/tab-settings.html:

<li class="item item-toggle">
     National Insurance {{ni_toggle}}
     <label class="toggle toggle-positive">
       <input type="checkbox" ng-model="ni_toggle" ng-change="updateLocalStorage()" id="has_national_insurance" name="has_national_insurance">
       <div class="track">
         <div class="handle"></div>
       </div>
     </label>
  </li>

Working example of the problem

【问题讨论】:

  • 我能看到整个控制器吗?我需要更多背景信息。
  • 这就是我现在在 SettingsCtrl 中的全部内容。以上更新^
  • 你的问题是 $scope.ni_toggle 没有定义。可能看起来“很好”,但如果您查看控制器,您没有任何内容可以显示$scope.ni_toggle = blah blah blah,这对我来说是一个死的赠品。

标签: javascript angularjs checkbox ionic-framework


【解决方案1】:

我不熟悉 Ionic 的古怪之处(如果有的话),但从一般 JS 的角度来看,您的代码似乎存在一些问题。

  1. 你没有初始化ni_toggle

  2. 您正在使用ngClick,它将在模型被ngModel 指令更新之前被触发。
    你应该改用ngChange

  3. 在 Angular 中,您应该使用 $window 而不是 window(它不会造成伤害,并且在许多情况下(例如测试)证明是有用的)。

  4. 请注意,localStorage 只能存储字符串(不能存储布尔值)。所以,即使你传递了false,它也会被存储为'false',当转换为布尔值时相当于true


考虑到上述情况,您的代码应如下所示:

<input type="checkbox" ng-model="ni_toggle" ng-change="updateLocalStorage()" ... />

.controller('SettingsCtrl', function($scope, $window, $ionicPlatform) {
    $ionicPlatform.ready(function() {
        // Ready functions
    });

    $scope.ni_toggle = $window.localStorage.getItem('has_national_insurance') === 'true';
    $scope.updateLocalStorage = function () {
        $window.localStorage.setItem('has_national_insurance', $scope.ni_toggle);
        console.log($scope.ni_toggle);
    };
});

另请参阅此short demo

【讨论】:

  • 我尝试按原样使用您的演示代码,无论状态如何,它都保持为“真”。可能与我的 UIRouter 设置有关吗?我已经用 app.js、controllers.js 和 templates/tab-settings.html 的完整代码更新了原始问题。感谢您到目前为止的帮助:)
  • @ian:您似乎还没有成功地按原样使用我的代码。请参阅注释 nr.4 并查看我的实现(尤其是 === "true")部分。
  • 啊,那是我测试并忘记撤消更改。我已经更新了代码,但即使使用 === "true" 它仍然只在控制台中记录 "true"。我在想,在我更好地理解这些概念之前,我可能不应该使用离子/角度。获取复选框的状态应该不难。
  • @ian:你把ngClick改成ngChange了吗?当它可能是也可能不是复制/粘贴问题时,尝试调试问题是一种令人沮丧的事情。如果您可以在 plunkr 中重现该问题,那将是最好的,所以我们有一些工作要做。获取复选框的值确实并不困难(正如我的回答所证明的那样:))。
  • 给你,我的应用程序结构的 plnkr 使用你的代码。 tab-settings.html 中的 {{ni_toggle}} 显示正确的状态,但它只在控制台中记录“true”:plnkr.co/edit/s88qJ7jnJe1rWFVxYjUp?p=preview
【解决方案2】:

不久前,我在使用 ionic 应用程序显示用户信息时遇到了类似的情况。我面前没有我的原始源代码,但我很确定这就是您需要的方式。

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

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

        this.toggle = true; // make sure its defined somewhere

        $scope.ni_toggle = function() {
            return this.toggle;
        }

        $scope.updateLocalStorage = function() {
            window.localStorage.setItem(
                'has_national_insureance',
                $scope.ni_toggle
            );
            console.log($scope.ni_toggle);
        }

    });

希望这能让你朝着正确的方向前进。

编辑 请参阅 ExpertSystem 的答案。他回答得比我好。

【讨论】:

    【解决方案3】:

    控制器中不需要任何函数定义

     <script>
     angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.checkboxModel = {
       value1 : true,
       value2 : 'YES'
     };
    }]);
    

    <form name="myForm" ng-controller="ExampleController">
    <label>Value1:
    <input type="checkbox" ng-model="checkboxModel.value1">
    </label><br/>
    <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.value2"
           ng-true-value="'YES'" ng-false-value="'NO'">
    </label><br/>
    <tt>value1 = {{checkboxModel.value1}}</tt><br/>
    <tt>value2 = {{checkboxModel.value2}}</tt><br/>
    

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多