Problems writing out variables in AngularJS using Ionic - javascript

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">

Related

Angular 'undefined is not a function' defining component

I had working ionic code to allow the user to input a list, which I tried to factor out into a component for re-use. But on running I get the error undefined is not a function in line 4 of the js. How can this be fixed?
/*jshint multistr: true */
var app = angular.module('ionicApp', ['ionic']);
app.component('inputlist',{
bindings: {label: '#'},
template: '\
<div class="list">\
<div class="item item-button-right">\
<ion-label floating>Enter {{$ctrl.label}} below then press +</ion-label>\
<input type="text" ng-model="nameinput.name"></input>\
<button class="button button-assertive" ng-click="addItem()">+</button>\
</div>\
<div class="item item-button-right" ng-repeat="item in items track by $index">\
<ion-label>{{item.name}}</ion-label>\
<button class="button button-positive" ng-click="items.splice($index,1)">-</button>\
</div>\
</div>',
controller: function() {
this.items = [];
this.nameinput = {name:''};
this.addItem = function(){
var name = this.nameinput.name.trim();
if (name!=="")
{
this.items.push({name:name});
this.nameinput={name:""};
}
};
}
});
html
<!DOCTYPE html>
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic-AngularJS-Cordova</title>
<!-- Ionic framework - replace the CDN links with local files and build -->
<link href="lib/ionicframework/ionic.min.css" rel="stylesheet">
<script src="lib/ionicframework/ionic.bundle.min.js"></script>
<script src="js/app.js"></script>
<script src="cordova.js"></script>
</head>
<body>
<ion-content>
<inputlist label="foo"></inputlist>
</ion-content>
</body>
</html>
You mentioned that you are using Ionic v1.0.0-beta1 in your project, which i believe that this version of ionic comes bundle with angular version below 1.3.
Component, on the other hand, is a new feature available in angular 1.5 and above. This explains why you got function is undefined in line 4 app.component() method.
I would suggest you to take either one of these 2 approach to resolve your issue:
1) Convert component to directive.
2) Upgrade the ionic to v1.3.2 (latest version) which supports angular 1.5

Data Not displaying in ionic and angular List

I am new to ionic and angular. was trying to create a list with json data
{"menu":[{"name":"Mixed Veg Wrap","image":"mix-veg-wrap.jpg","category":"WRAPS, Light Bites","spice_meter":"1","description":"Spicy mixed vegetables :)","rating":"3","price":"35","is_veg":"yes"},{"name":"Egg Wrap","image":"egg-wraps.jpg","category":"WRAPS, Light Bites","spice_meter":"0","description":"Double egg coating with Onion and Sauces!","rating":"4.9","price":"36","is_veg":"no"},{"name":"Cheese Melt Paneer","image":"cmp.jpg","category":"WRAPS, Special","spice_meter":"0","description":"Paneer in Reshmi Masala with melted Cheese","rating":"4.5","price":"91","is_veg":"yes"},{"name":"Prawns Tikka","image":"prawan.jpg","category":"WRAPS, Special","spice_meter":"1","description":"Prawns in spicy tikka masala.","rating":"3.5","price":"110","is_veg":"no"}
Here is my controller the 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'
angular.module('starter', ['ionic'])
.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();
}
});
}).controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.menu = data;
});
}]);
Here 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">
<!-- 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">
<ion-pane>
<ion-header-bar class="bar-dark">
<h2 class="title">Artist List</h2>
</ion-header-bar>
<div class="bar bar-subheader
item-input-inset bar-light">
<label class="item-input-wrapper">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" placeholder="Search">
</label>
</div>
<ion-content ng-controller="ListController"
class="has-subheader">
<ion-list>
<ion-item ng-repeat='item in menu'
class="item-text-wrap">
<h2>{{item.name}}</h2>
<img ng-src="img/{{item.image}}" />
<h3>{{item.category}}</h3>
<h3>{{item.spice_meter}}</h3>
<h3>{{item.description}}</h3>
<h3>{{item.rating}}</h3>
<h3>{{item.price}}</h3>
<h3>{{item.is_veg}}</h3>
</ion-item>
</ion-list>
</ion-content>
</ion-pane>
</body>
</html>
Nut the resultant o/p is blank list
i checked the console which shows
ionic.bundle.js:17752 XHR finished loading: GET
"http://192.168.1.201:8100/js/data.json".(anonymous function) #
ionic.bundle.js:17752sendReq # ionic.bundle.js:17553serverRequest #
ionic.bundle.js:17269processQueue # ionic.bundle.js:21114(anonymous
function) # ionic.bundle.js:21130Scope.$eval #
ionic.bundle.js:22326Scope.$digest # ionic.bundle.js:22142Scope.$apply
# ionic.bundle.js:22431bootstrapApply # ionic.bundle.js:9373invoke #
ionic.bundle.js:12110doBootstrap # ionic.bundle.js:9371bootstrap #
ionic.bundle.js:9391angularInit # ionic.bundle.js:9285(anonymous
function) # ionic.bundle.js:34050trigger #
ionic.bundle.js:10669eventHandler # ionic.bundle.js:10939
Please help!!
Make sure that the path you are seeing in browser console http://192.168.1.201:8100/js/data.json is correct.
Then while assigning menu use data.menu instead of just data
.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.menu = data.menu; //assigning menu
});
}]);

Impress.js and AngularJS Controller

I am running an AngularJS application/controller. My goal is to initialize and use the impress.js library on a page that is being dynamically loaded into my main home page. However, when I try to initialize the library, the page does not load. Attached is a snippet of the controller and html file.
NOTE: When I print the impress() object to the console, it is not null, and has the required functions. It is my suspicion that the impress() object is not hooking up to the page correctly.
Controller:
'use strict';
// Create the angular module
var cmodule = angular.module('coverage', ['ngRoute'])
// Create the coverage controller
cmodule.controller('coverageController', function($scope) {
console.log("Entering controller");
function require(script) {
$.ajax({
url: script,
dataType: "script",
async: true, // <-- This is the key
success: function () {
console.log(impress());
impress().init();
},
error: function () {
throw new Error("Could not load script " + script);
}
});
}
console.log("About to require");
angular.element(document).ready(function () {
require("/content/libraries/impress.js");
});
});
HTML File:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=1024" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>My Coverage</title>
<link rel="stylesheet" href="/content/styles/team1.css">
</head>
<body class="impress-not-supported">
<!--
For example this fallback message is only visible when there is `impress-not-supported` class on body.
-->
<div class="fallback-message">
<p>Your browser <b>doesn't support the features required</b> by impress.js, so you are presented with a simplified version of this presentation.</p>
<p>For the best experience please use the latest <b>Chrome</b>, <b>Safari</b> or <b>Firefox</b> browser.</p>
</div>
<!-- Now the fun begins -->
<div id="impress">
<!-- The background image -->
<div class="present" data-x="0" data-y="0">
<!-- Place Image here -->
</div>
<!-- Example content -->
<div id="url-ident" class="step" data-x="0" data-y="0">
<q>Ready to view your coverage?</q>
</div>
<!-- Example content -->
<div id="step1" class="step" data-x="500" data-y="0">
<p>Questions start here!</p>
</div>
</div> <!-- /div impress -->
<script type="text/javascript" src="/content/libraries/impress.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<!--script type="text/javascript">impress().init();</script-->
</body>
</html>
This problem was fixed by using the jmpress.js library instead, found here.

angular/ionic - model does not update $scope in controller

I am a newb with angularjs and I am trying something that I believe should be very simple ... but turns out I am not figuring it out.
I have a $scope variable that I want to double bind (using ng-model) to a textarea. I was able to make it work on js fiddle websites but now on my code. I have tried to strip everything down to just a few lines and it still doesn't work, the controller is never updated.
this is my code:
js/main.js
var app=angular
.module('noclu', ['ionic', 'app.controllers'])
.config(function ($stateProvider, $urlRouterProvider){
$stateProvider
.state('menu.main', {
url: "/main",
views: {
'menuContent': {
templateUrl: 'templates/main.html',
controller: 'MainCtrl'
}
}
});
$urlRouterProvider.otherwise("/menu/main");
});
js/controller.js
angular
.module('app.controllers', [])
.controller('MainCtrl', function ($scope){
$scope.src='---';
$scope.get_feeds=function(){
//seems like that here "this" is actually the textarea ??
//$scope.src is always whatever has been set in the controller
console.log('this:'+this.src); //this output whatever I enter in the textarea
console.log('scope:'+$scope.src); //this always output '---'
};
});
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">
<link rel="icon" type="image/png" href="favicon.png">
<title>NoClu</title>
<link href="lib/ionic/css/ionic.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/main.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app="noclu">
<ion-nav-view></ion-nav-view>
</body>
</html>
template/main.html
<ion-view view-title="NoClu" >
<ion-content class="padding" id="src-wrapper-center">
<div ng-class="vertical_center">
<div id="src-wrapper">
<div>
<div class="padding src-title">What are you in the mood for ?</div>
<div class="item" id="src-txt-wrapper">
<textarea id="src" ng-model="src"></textarea>
</div>
<button id="search" class="button button-block button-large button-balanced" ng-click="get_feeds()" >
Let's eat
</button>
</div>
</div>
</div>
</ion-content>
</ion-view>
UPDATE - I made it work, but why ?
I made it work by changing $scope.src='---'; to $scope.src={body:'---'}; and then changing the ng-modal to src.body. but.. WHY did not work the other way as it works for boolean?
Using directly $scope. is not a good practice in angularJS. There are various post of it, more concernign $scope inheritence.
For exemple : http://learnwebtutorials.com/why-ng-model-value-should-contain-a-dot
Therefore, your need to change your model like that :
$scope.myModel = {};
$scope.myModel.src = "---"
And your html to bind to myModel.src

ionicframework CRUD operation using SQLite

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;
};

Categories

Resources