javascript 在 Ionic Framework (AngularJS) 中获取和设置一个复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25080212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get and set a checkbox in Ionic Framework (AngularJS)
提问by Ian
I need to track when a user changes the state of a checkbox in Ionic, save it to localStorage, and then use it to load again later - so it remembers their settings.
我需要跟踪用户何时更改 Ionic 中复选框的状态,将其保存到 localStorage,然后稍后使用它再次加载 - 这样它就会记住他们的设置。
My toggle code looks like this:
我的切换代码如下所示:
<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>
And in my controller I have:
在我的控制器中,我有:
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 );
}
})
However, it logs out to the console as undefined
. If I explicitly set $scope.ni_toggle = false;
it will log false and won't update to true when I toggle the checkbox to on.
但是,它以undefined
. 如果我明确设置$scope.ni_toggle = false;
它会记录 false 并且当我将复选框切换为 on 时不会更新为 true。
EDIT:
编辑:
app.js:
应用程序.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:
控制器.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) {
});
templates/tab-settings.html:
模板/标签设置.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>
回答by gkalpak
I am not familiar with Ionic's oddities (if there are any), but from a general JS perspective there seem to be a few issues with your code.
我不熟悉 Ionic 的奇怪之处(如果有的话),但从一般的 JS 角度来看,您的代码似乎存在一些问题。
You are not initializing
ni_toggle
.You are using
ngClick
which will get fired beforethe model has been updated by thengModel
directive.
You should usengChange
instead.In Angular, you should use
$window
instead ofwindow
(it doesn't hurt and it can prove useful in many cases (e.g. testing)).Note that
localStorage
can only store strings (not booleans). So, even if you passfalse
, it will be stored as'false'
, which is equivalent totrue
when cast to boolean.
您没有初始化
ni_toggle
.您正在使用
ngClick
which 将在指令更新模型之前被触发ngModel
。
你应该ngChange
改用。在 Angular 中,您应该使用
$window
而不是window
(它不会受到伤害并且在许多情况下(例如测试)它可以证明是有用的)。请注意,
localStorage
只能存储字符串(不是布尔值)。因此,即使您通过false
,它也会存储为'false'
,这相当于转换true
为布尔值。
Taking the above into account, your code should look like this:
考虑到上述情况,您的代码应如下所示:
<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);
};
});
See, also, this short demo.
另请参阅此简短演示。
回答by pattmorter
I ran into a similar situation for displaying user information a while ago with my ionic app. I don't have my original source code in front of me but I'm pretty sure this is how you need to do it.
不久前,我在使用 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);
}
});
Hope this gets you going in the right direction.
希望这能让你朝着正确的方向前进。
EDITSee ExpertSystem's answer. He answered it way better than I could.
编辑请参阅 ExpertSystem 的答案。他回答得比我好。
回答by Baljeet Singh
No need of any function definition in controller
控制器中不需要任何函数定义
<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/>