ionicframework CRUD operation using SQLite - javascript

I have added the ngcordova SQLite plugin required to create this sample app.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Crud & SQLite</h1>
</ion-header-bar>
<ion-content ng-controller="AccountController">
<form ng-submit="addAccount()">
<div class="list">
<label class="item item-input item-stacked-label">
<span class="input-label">First Name</span>
<input type="text" placeholder="John" ng-model="firstnameText">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Last Name</span>
<input type="text" placeholder="Suhr" ng-model="lastnameText">
</label>
<div class="padding">
<button class="button button-block button-positive">Create Account</button>
</div>
</div>
</form>
<ul class="list list-inset">
<li class="item item-divider">
{{accounts.length}} records
</li>
<li class="item" ng-repeat="account in accounts">
<i class="icon ion-person"></i> -
<span>{{account.firstname}} {{account.lastname}}</span>
</li>
</ul>
</ion-content>
</ion-pane>
</body>
</html>
app.js
var db = null;
angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
db = $cordovaSQLite.openDB({ name: "my.db" });
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXIST people (id integer primary key, firstname text, lastname text)");
});
})
.controller('AccountController', function($scope, $cordovaSQLite) {
$scope.accounts = function() {
var query = "SELECT firstname, lastname FROM people";
$cordovaSQLite.execute(db, query);
}
$scope.addAccount = function(){
var query = "INSERT INTO people (firstname, lastname) VALUES (?, ?)";
$cordovaSQLite.execute(db, query, [$scope.firstnameText, $scope.lastnameText]);
$scope.firstnameText = '';
$scope.lastnameText = '';
}
});
I've running my app on my device, and nothing was added to list which mean im not saving anything to the database. Any help please? Thankyou

I had this problem - after some research I solved it by waiting for Cordova's deviceready event before loading Angular. Check the API docs for how to do a manual Angular initialisation
Basically you need to remove your ng-app directive, and call angular.bootstrap on the element that it was previously on once Cordova's deviceready event has fired
I added a delayedAngular.js file like so (don't forget to add it as a <script> in your index.html)
angular.element(document).ready(function() {
console.log("BOOTSTRAPPING...");
if (window.cordova) {
document.addEventListener('deviceready', function() {
console.log("window.cordova detected");
angular.bootstrap(document.body, ['myCoolApp']);
}, false);
} else {
console.log("window.cordova NOT detected");
angular.bootstrap(document.body, ['myCoolApp']);
}
});
In the above code replace myCoolApp with the name of your main app module. I'll try to find the blog post where I found this for due credit.
I found it very helpful to have it fall back to a WebSQL database for testing in the browser as well, as SQLite debugging on device is a pain. I used the code below in my app - it uses Angular promises so make sure you are familiar with them (make sure you also inject $window if you want the alerts. I haven't rooted my phone so couldn't directly check the SQLite database on device :-/)
var initDB = function(dbName){
$log.log("Opening DB...");
var q = $q.defer();
var db;
if($cordovaSQLite && $window.sqlitePlugin !== undefined){
$window.alert("SQLite plugin detected");
db = $cordovaSQLite.openDB({ name: dbName });
q.resolve(db);
}
else {
db = $window.openDatabase(
dbName,
"0.0.1",
"My DB",
200000,
function(){
$window.alert("Created WebSQL DB!");
}
);
q.resolve(db);
}
return q.promise;
};

Related

Problems writing out variables in AngularJS using Ionic

Using the ngCordova Barcode Scanner i am storing the barcode number and the barcode format in variables to output them in the app view. I wan't to be able to scan multiple barcodes which have to update the stored variable every time writing out the new barcode number and format. But when I scan multiple barcodes it just keeps on appending "Barcode: + barcodeNumber " instead of replacing. I cannot figure out what I am doing wrong. The app screenshot shows the problem.
App screenshot image
Here's my index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Barcode Scanner</h1>
</ion-header-bar>
<ion-content ng-controller="barcodeController">
<button class="button button-full button-positive" ng-click="scanBarcode()">
Scan Now
</button>
<div class="card">
<div class="item item-divider">Barcode Data</div>
<div class="item item-text-wrap">Barcode: {{barcodeNumber}}</div>
<div class="item item-text-wrap">Format: {{barcodeFormat}}</div>
</div>
</ion-content>
</ion-pane>
</body>
</html>
Here's my app.js code:
// 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'
var ionScanner = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
ionScanner.controller("barcodeController", function($scope, $cordovaBarcodeScanner) {
$scope.scanBarcode = function() {
$cordovaBarcodeScanner.scan().then(function(barcodeData){
if (barcodeData.cancelled == 1){
// Do nothing
}else{
// Assign barcode data
$scope.barcodeNumber = "";
$scope.barcodeNumber = barcodeData.text;
$scope.barcodeFormat = barcodeData.format;
}
}, function(error){
console.log("Error: " + error);
});
}
});
So, it turned out that this error/bug was a result of the iOS automated phone number recognition. I solved the issue by adding a no format for phone numbers.
<meta name="format-detection" content="telephone=no">

How to properly setup AngularJS files

Im familiar with the standard way of setting up a angularjs project, what I'm trying to do is set the app with separate files for different controllers and directives based on the page. See below for better explanation.
www /
app.js
index.html
login /
loginDirective.js
loginPage.html
This is my apps.js file
// 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'
(function () {
'use strict';
angular.module('app', ['ionic']);
})();
var app=angular.module('app');
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
this is my loginDirective.js
(function () {
'use strict';
var app=angular.module('app');
app.config(function($stateProvider) {
$stateProvider
.state('login', {
url: '/login',
template: '<loginDirective></loginDirective>'
})
})
app.directive('loginDirective', loginDirective);
function loginDirective() {
var directive = {
restrict : 'EA',
templateUrl : 'loginPage.html',
controller : loginController,
controllerAs : 'lg',
bindToController : true
};
return directive;
}
function loginController() {
var lg = this;
lg.test = 'this is a test';
console.log('RETURN = %s', 'test');
}
})();
this is my index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="login/loginDirective.js"></script>
</head>
<body ng-app="app" animation="slide-left-right-ios7">
<div>
<div>
<ion-nav-bar class="bar-dark">
<ion-nav-title>Sample APP</ion-nav-title>
<ion-nav-back-button class="button-icon icon ion-ios-arrow-back">Back</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view ></ion-nav-view>
</div>s
</div>
</body></html>
last but not least loginPage.html
<html>
<head>
</head>
<body>
<div login-directive></div>
<ion-view view-title="Login" name="login-view" class="scroll-bg" hide-nav-bar="true">
<ion-content class="padding">
<div align="center" class="imagecontent">
<div style="text-align: center">
<img ng-src="img/logos#2x.png" width="250px">
</div>
</div>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Username" style="color: #ffffff" ng-model="data.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" style="color: #ffffff" ng-model="data.password">
</label>
</div >
<div class="" >
<div class="">
<button class=" button button-block button-dark" ng-click="login(data)">LOG IN</button>
</div>
</div>
</ion-content>
<div style="position: absolute; bottom: 10%; width: 100%">
<div style="text-align: center">
<img ng-src="img/FNC_Logo.png" width="150px">
</div>
</div>
<ion-footer-bar align-title="right" class="footer-bg">
<div class="col text-right" ng-click="doSomething()">
<button class="button footerbtn-bg" ></button>
</div>
</ion-footer-bar>
</ion-view>
</body>
</html>
What am I doing incorrectly that causes my loginPage.html to not show up?
I may be wrong, because I a novice with AngularJS, but if I were you, I firstly would try to change:
templateUrl : 'loginPage.html'
into:
templateUrl : 'login/loginPage.html'
I came to such conclusion, because you included loginPage.js file in index.html, so it tries look loginPage.html in www directory, or in directory where it was called.
I met such case like yours today, but with images.
You state definition has problems:
$stateProvider
.state('login', {
url: '/login',
//This should be kebab-case
template: '<login-directive></login-directive>'
//NOT camelCase
//template: '<loginDirective></loginDirective>'
})
})
But I am not sure why you are using a directive for that state when you could define the state with a controller:
.state('login', {
url: '/login',
templateUrl : 'loginPage.html',
controller : loginController,
controllerAs : 'lg'
});
Try moving <div login-directive></div> into the ion-view.
Also inspect the console to see if console.log('RETURN = %s', 'test'); is actually outputted. At least you'd then know if the state is active or not.
Like #georgeawg said, you're overcomplicating this by using a directive as template. Why you did that in this example is beyond me. Also, your $state config should be in your app.js file.

Camera doesnt start using cordova camera plugin and angular js

I want to capture image on click of a button but it doesn't work.I have done many troubleshooting but still in vain.Below i am posting my code and cordova plugins list . Please suggest the changes required.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="js/ng-cordova.js"></script>
<script src="js/cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">M-Services </h1>
</ion-header-bar>
<ion-content ng-controller="ExampleController">
<input type="text" ng-model="text1" placeholder="Username "/>
<input type="text" ng-model="text2" placeholder="Password "/>
<button class="button" ng-click="insert(text1,text2)">SignUp</button>
<button class="button" ng-click="login(text1,text2)">Login</button>
<div class="list card" ng-controller="FirstController">
<div class="item item-image">
<img ng-src="{{picturepath}}"/>
</div>
<div class="padding">
<button ng-click="takePicture()" class="button button-block button-calm">Take Picture</button>
</div>
</div>
</ion-content>
<!-- <ion-view view-title="Login" name="LoginView">
<ion-content>
<div class="list list-inset">
<form name="loginForm" ng-controller="LoginController"
ng-submit="login(credentials)" novalidate>
<label for="username">Username:</label>
<input type="text" id="username"
ng-model="credentials.username">
<label for="password">Password:</label>
<input type="password" id="password"
ng-model="credentials.password">
<button type="submit">Login</button>
</form>
</div>
<label class="checkbox">
<input type="checkbox" name="rememberme" value="remember">Remember me | Forgot Password
</label>
<!-- <ion-checkbox ng-model="isChecked">Remember me</ion-checkbox> | Forgot Password<br>
</ion-content>
</ion-view>
</ion-pane>-->
</body>
</html>
app.js
var db = null;
var records=null;
var validation=null;
var example = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
db = window.openDatabase("my.db","1.0","my.db",100000);
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS signup (firstName text,lastName text,userName text,city text,contact_no number,email text)");
// $cordovaSQLite.execute(db, "DELETE from people");
window.alert("Database Created .. !")
});
});
example.controller("FirstController",function($scope,$cordovaCamera) {
$scope.picturepath = 'http://placehold.it/50x50';
$scope.takePicture = function (){
var options = {
destinationType: Camera.DestinationType.DATA_URL,
encodingType: Camera.EncodingType.JPEG,
};
$cordovaCamera.getPicture(options).then(function(imageData) {
//var image = document.getElementById('myImage');
$scope.picturepath = "data:image/jpeg;base64" + imageData;
}, function(err) {
window.alert(err);
});
}
});
example.controller("ExampleController", function($scope, $cordovaSQLite) {
$scope.insert = function(firstname, lastname) {
var query = "INSERT INTO people (firstname,lastname) VALUES (?,?)";
$cordovaSQLite.execute(db, query, [firstname, lastname]).then(function(res) {
window.alert("Record Inserted Successfully..!!");
}, function (err) {
console.error(err);
});
}
$scope.login = function(firstname,lastname) {
$cordovaSQLite.execute(db,"SELECT firstname, lastname FROM people where firstname=? and lastname=?",[firstname,lastname]).then(function(res) {
if(res.rows.length >0)
window.location="login.html";
}, function (err) {
console.error(err);
});
}
$scope.clicked=function()
{
}
$scope.signup=function(firstName,lastName,userName,city,number_no,email)
{
var query = "INSERT INTO signup (firstName,lastName,userName,city,contact_no,email) VALUES (?,?,?,?,?,?)";
$cordovaSQLite.execute(db, query, [firstName,lastName,userName,city,number_no,email]).then(function(res) {
window.alert("Records Inserted ..!1");
}, function (err) {
console.error(err);
});
}
});
Plugins list
cordova-plugin-camera 1.2.0 "Camera"
cordova-plugin-console 1.0.2 "Console"
cordova-plugin-device 1.1.0 "Device"
cordova-plugin-file 3.0.0 "File"
cordova-plugin-media-capture 1.1.0 "Capture"
cordova-plugin-splashscreen 3.0.0 "Splashscreen"
cordova-plugin-statusbar 2.0.0 "StatusBar"
cordova-plugin-whitelist 1.2.0 "Whitelist"
cordova-sqlite-storage 0.7.15-pre "Cordova sqlite storage plugin"
ionic-plugin-keyboard 1.0.8 "Keyboard"
Error:
ReferenceError: Camera is not defined
at Scope.$scope.takePicture
Your Device Ready might have not fired yet so wrap your camera code inside device ready event listener
document.addEventListener("deviceready", function () {
$scope.takePicture = function (){
var options = {
destinationType: Camera.DestinationType.DATA_URL,
encodingType: Camera.EncodingType.JPEG,
};
$cordovaCamera.getPicture(options).then(function(imageData) {
//var image = document.getElementById('myImage');
$scope.picturepath = "data:image/jpeg;base64" + imageData;
}, function(err) {
window.alert(err);
});
}

Undefined Ionic form input

I'm following this tutorial to create a simple Ionic to do app.
This is my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="myApp" ng-controller="todoCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">To Do</h1>
</ion-header-bar>
<ion-content>
<div class="item item-input-inset">
<label class="item-input-wrapper">
<!-- The actual input tag which is bound to the todoInput using ng-model -->
<input type="text" placeholder="Add New Item" ng-model="todoInput" size="100">
</label>
<!-- Our button thay will call our funtion to add a new todo item -->
<button class="button button-small" ng-click="todoAdd()">
Add Item
</button>
</div>
<div ng-repeat="x in todoList">
<li class="item item-checkbox">
<label class="checkbox">
<!-- this is the checkbox element, you will see it is bound to the done setting in the items array -->
<!-- When clicked it calls the update function to update the item to its done status -->
<input type="checkbox" ng-model="x.done" ng-click="update()">
</label>
<!-- this is a span tag that shows the item text, I am using ng-bind, instead of the span tag we could have used {{x.todoText}} as well -->
<span>{{x.todoText}}</span>
</li>
</div>
<!-- the remove button will call the remove function and remoave all items that are marked done -->
<button class="button button-block button-assertive" ng-click="remove()">
Remove Checked Items
</button>
</ion-content>
</ion-pane>
</body>
</html>
And this my app.js so far:
var app = angular.module('myApp', ['ionic']);
app.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) {
StatusBar.styleDefault();
}
});
});
app.controller('todoCtrl', ['$scope', function($scope) {
//if local storage is null save the todolist to local storage
if (localStorage.getItem("mytodos") == null){
$scope.todoList = [ {todoText:'Create app', done:false} ];
localStorage.setItem("mytodos", angular.toJson($scope.todoList));
} else {
//get the todolist from local storage
$scope.todoList = angular.fromJson(localStorage.getItem("mytodos"));
}
// Add an item function
$scope.todoAdd = function() {
console.log($scope.todoInput);
};
}]);
When I click on the todoAdd() button, I get undefined inside my console even though I typed something inside the input.
Am I doing any mistakes here?
Solved.
HTML
<input type="text" placeholder="Add New Item" ng-model="form.todoInput" size="100">
<button class="button button-small" ng-click="todoAdd(form)">Add Item</button>
JS
$scope.todoAdd = function(formData){
console.log(formData);
};

How to send form data from ionic app to parse.com MBaaS using REST API

I'm extremely new to Ionic/Angular (Started today itself out of necessity),
Taking help of tutorials as well as documentations,
I had been creating a demo/test app that submits data to Parse.com MBaaS service.
But something somewhere is going wrong, clueless on how to go add the three form fields
Details: the App name is TestApp
Class/Table name is data
there are three columns, fname, lname and uname (for firstname lastname and username)
Here's the code I've been following. Any help would be deeply obliged.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<div>
<div>
<ion-nav-bar class="bar-stable">
<ion-nav-back-button class="button-icon icon ion-ios7-arrow-back">Back</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</div>
</div>
<!-- Center content -->
<ion-view title="Add Data">
<ion-content padding="true" scroll="false" class="has-header">
<div class="spacer" style="height: 100px;"></div>
<form ng-controller="defaultCtrl">
<ion-list>
<label class="item item-input">
<span class="input-label">First Name</span>
<input type="text" placeholder="First Name here" name="fname" ng-model="starter.fname">
</label>
<label class="item item-input">
<span class="input-label">Last Name</span>
<input type="text" placeholder="Surname Here" name="lname" ng-model="starter.lname">
</label>
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" placeholder="Username here" name="uname" ng-model="starter.uname">
</label>
</ion-list>
<button class="button button-calm button-block" type='submit' ng-click="create(starter)">Add data</button>
</form>
</ion-content>
</ion-view>
<script type="text/javascript">
angular.module('starter',['ionic']).factory('starter',['$http','PARSE_CREDENTIALS',function($http,PARSE_CREDENTIALS){
return {
create:function(data){
return $http.post('https://api.parse.com/1/classes/data',data,{
headers:{
'X-Parse-Application-Id': PARSE_CREDENTIALS.APP_ID,
'X-Parse-REST-API-Key':PARSE_CREDENTIALS.REST_API_KEY,
'Content-Type':'application/json'
}
});
}
}
}]).value('PARSE_CREDENTIALS',{
APP_ID: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
REST_API_KEY:'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
});
angular.module('starter', ['ionic'])
.controller("defaultCtrl", function ($scope) {
$scope.starter = {};
$scope.create=function(){
starter.create({fname:$scope.starter.fname}).success(function(data){
});
});
</script>
</body>
</html>
Set the authentication headers
PARSE_HEADER_CREDENTIALS = {
"x-parse-application-id": "PARSE-APPLICATION-ID",
"x-parse-rest-api-key": "PARSE-REST-API-KEY"
};
code
addObject: function (_params) {
// for POST, we only need to set the authentication header
var settings = {
headers: PARSE_HEADER_CREDENTIALS,
};
// for POST, we need to specify data to add, AND convert it to
// a string before passing it in as seperate parameter data
var dataObject = {
"name": _params.name,
"room": _params.room,
};
var dataObjectString = JSON.stringify(dataObject);
// $http returns a promise, which has a then function
return $http.post(baseURL + 'classes/stuff', dataObjectString, settings)
.then(function (response) {
// In the response resp.data contains the result
// check the console to see all of the data returned
console.log('addObject', response);
return response.data;
});
},
complete example posted in project here:
https://github.com/aaronksaunders/info-rest-api-ionic-sample

Categories

Resources