1.添加sqlite 组件
cordova plugin add https://github.com/litehelpers/Cordova-sqlite-storage.git --save
2.编写代码 app.js =>run=> $ionicPlatform.ready 添加
if(window.cordova ) { ltdb = $cordovaSQLite.openDB({name: "ltapp.db", location: 1}); //创建用户表 $cordovaSQLite.execute(ltdb, "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, phonenumber INTEGER, password TEXT)"); $cordovaSQLite.execute(ltdb, 'SELECT COUNT(*) FROM users ').then(function (res) { if (res.rows.length < 0) { var query = "INSERT INTO users (name,email,phonenumber,password) VALUES ( ?, ?, ?, ?)"; $cordovaSQLite.execute(ltdb, query, ['admin', 'sulin11026@163.com', '13683365354', '123']).then(function (result) { console.log("success"); }, function (error) { }) } }, function (error) { console.log(error); } ); }
controllers .js
controller('LoginCtrl',['$scope', '$state', '$ionicPopup', 'AuthService', function($scope, $state, $ionicPopup, AuthService) {
$scope.login = function() {
var user= $scope.user;
AuthService.login(user.uname, user.pwd).then(function(authenticated) {
$state.go('tabs.home', {}, {reload: true});
$scope.setCurrentUsername(user.username);
}, function(err) {
var alertPopup = $ionicPopup.alert({
title: '登录失败',
template: '请输入正确的账号密码!'
});
});
};
}])
servcies.js
.factory('AuthService',['$q', '$http','$cordovaSQLite', function($q, $http,$cordovaSQLite) {var username = '';var login = function(name, pw) { return $q(function(resolve, reject) { try { $cordovaSQLite.execute(ltdb, "SELECT * FROM users WHERE name = ? ",[name]).then( function(res) { if (res.rows.length > 0) { if(pw.toLocaleUpperCase()==res.rows.item(0).password.toLocaleUpperCase()){ resolve('Login success.'); } }else{ reject('Login Failed.'); } }, function(error) { reject('Login Failed.'); } ); } catch(ex){ } }); };return { login: login }; }])
index.html
<ion-view class="login" hide-nav-bar="true" style="z-index: 1" cache-view="false"> <form ng-submit="login()" name="theform"> <div id="login"> <div class="logo"><img src="img/fixed/logo.png"></div> <div class="fill"> <label class="item item-input ion-ios-person-outline"> <input type="text" placeholder="账号" ng-model="user.uname" ng-focus="hide='1'" ng-blur="hide='1'" ng-required="true" > </label> <label class="item item-input ion-ios-locked-outline"> <input type="password" placeholder="密码" ng-model="user.pwd" ng-required="true" ng-focus="hide='1'" ng-blur="hide='1'" > </label> <label class="btn"> <button class="button button-block button-light" type="submit">登录</button> </label> </div>
以上测试正常通过,如果有问题需要耐心慢慢调试