im newbie on ionic development i have an app that can uploading image into a serve with a certain paramater and using post method to upload it. my problem is can i uploading image using http.post angular on ionic?based on this forum
https://forum.ionicframework.com/t/file-upload-using-http-post-multi-form-data/10454
and this
https://forum.ionicframework.com/t/image-upload-to-api-service-using-http-post/36481
its recommended to using cordova file transfer how can i use it with my certain parameter
what i have done its like this
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>
<script src="http://code.highcharts.com/adapters/standalone-framework.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://rawgit.com/pablojim/highcharts-ng/master/src/highcharts-ng.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" ng-controller="homeController">
<ion-pane>
<ion-nav-title>
<span>Upload Foto</span>
</ion-nav-title>
<ion-content class="padding">
<button class="button button-block button-dark" ng-click="selImages()">
Select Images
</button>
<button ng-show="images.length > 0" class="button button-block button-stable" ng-click="shareAll()">
Share All
</button>
<div class="list card" ng-repeat="img in images">
<div class="item item-image">
<img ng-src="{{img}}">
</div>
<div class="item tabs tabs-secondary tabs-icon-left">
<a class="tab-item assertive image-option" href="#" ng-click="removeImage(img)">
<i class="icon ion-trash-a assertive"></i> Remove
</a>
</div>
</div>
</ion-content>
</ion-pane>
</body>
</html>
my controller
angular.module('starter', ['ionic','highcharts-ng','ngCordova'])
.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('ImagePickerCtrl', function ($scope, $rootScope, $cordovaCamera,$cordovaFileTransfer) {
$scope.images = [];
$scope.selImages = function () {
$scope.upload = function() {
}
window.imagePicker.getPictures(
function (results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
$scope.images.push(results[i]);
}
if (!$scope.$$phase) {
$scope.$apply();
}
}, function (error) {
console.log('Error: ' + error);
}
);
};
$scope.removeImage = function (image) {
$scope.images = _.without($scope.images, image);
};
$scope.shareImage = function (image) {
window.plugins.socialsharing.share(null, null, image);
};
$scope.shareAll = function () {
var url = "fendypradana.com/alfalahkeu/Apifalah/upload_buktibayar/format/json";
window.plugins.socialsharing.share(null, null, $scope.images);
var options = {
fileKey: "avatar",
fileName: "image.png",
chunkedMode: false,
mimeType: "image/png"
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function (result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function (err) {
console.log("ERROR: " + JSON.stringify(err));
}, function (progress) {
});
};
})
i have to include 2 paramater user_id=5 and keterangan=seragam
Any suggestions would really help.
Within the options variable
You are able to pass the params within the options object.
So
var options = {
fileKey: "avatar",
fileName: "image.png",
chunkedMode: false,
mimeType: "image/png",
params: {
user_id: 5,
keterangan: 'seragam'
}
};
Related
First I had a file called angular-controller.js where there was my app controller, and calling it in my html ng-controller it worked. Now I decide to make another file, a Factory file, to separate some functions from controller file, but now there are an error:
Error: Argument 'LoginController' is not a function, got undefined
at assertArg (angular.js:1099)
at assertArgFn (angular.js:1109)
at angular.js:4978
at angular.js:4560
at forEach (angular.js:137)
at nodeLinkFn (angular.js:4545)
at compositeLinkFn (angular.js:4191)
at publicLinkFn (angular.js:4096)
at angular.js:1660
at Object.$eval (angular.js:8218)
This is my angular-controller.js (with my controller):
var app = angular.module("StaffLogin", []);
app.controller("LoginController", function($scope, $http, restService) {
$scope.stafflogins = [];
$scope.staffLoginForm = {
email: "",
pass: ""
};
$scope.tokenStaffForm = {
idtokenstaff: -1,
tokenstaff: ""
};
$scope.staffForm = {
idstaff : -1,
staffType: {
idstaffType: -1,
type: ""
},
name: "",
surname: "",
birthDate: "",
phone: "",
gender: true,
working: true,
staffLogin: {
idstaffLogin: -1,
email: "",
pass: ""
}
};
$scope.submitCredentials= function() {
restService.login();
console.log($scope.staffLoginForm);
/* $http({
method : 'POST',
url : 'http://localhost:8080/FoodDrinkDispener/rest/tokenstaff',
data : angular.toJson($scope.staffLoginForm),
}).then(function successCallback(response) {
if (typeof response.data === 'object'){
_logsuccess(response)
return response.status;
}
else
_logerror(response);
},function (response) {
console.log($scope.tokenStaffForm);
_logerror(response);
}
);*/
}
function _SetToken(CurrentToken) {
sessionStorage.setItem("token", (CurrentToken === null) ? null : JSON.stringify(CurrentToken));
//console.log(CurrentToken);
}
function _logsuccess(response) {
console.log("Loggato correttamente");
console.log(response.status);
var CurrentToken = response.data;
_SetToken(CurrentToken);
}
function _logerror(response) {
console.log("Login fallito");
console.log(response.status);
_SetToken(null);
}
console.log(sessionStorage.getItem.toString);
});
This is my factory file called rest-services.js:
//'use strict';
var app = angular.module("StaffLogin", []);
app.factory("restService", function($scope, $http) {
var REST_URL = "http://localhost:8080/FoodDrinkDispener/rest/";
function _GetToken() {
var token = sessionStorage.getItem("token");
if (token !== null)
return JSON.parse(token);
}
function _SetToken(CurrentToken) {
sessionStorage.setItem("token", (CurrentToken === null) ? null : JSON.stringify(CurrentToken));
}
return {
login: function(loginform){
return $http({
method : 'POST',
url : REST_URL+'tokenstaff',
data : angular.toJson(loginform),
}).then(function successCallback(response) {
if (typeof response.data === 'object'){
// _logsuccess(response)
console.log("login andato a buon fine");
return response.status;
}
else
console.log("login error");
},function (response) {
console.log($scope.tokenStaffForm);
console.log("login error");
}
);
}
}
});
And this is my html file where I called the controller "LoginController"
<!DOCTYPE html>
<!-- saved from url=(0066)https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/signin/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="images/puzzle.png" />
<title>Login</title>
<!-- Bootstrap core CSS -->
<link href="./styles/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="./styles/signin.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body ng-app="StaffLogin" ng-controller="LoginController" ng-fa>
<div class="container">
<form class="form-signin" role="form" ng-controller="LoginController" ng-submit="submitCredentials()" novalidate>
<h2 class="form-signin-heading">Hai bisogno di autenticarti</h2>
<input type="email" class="form-control" placeholder="Email address" required="" autofocus="" id="email" ng-model="staffLoginForm.email">
<input type="password" class="form-control" placeholder="Password" required="" id="password" ng-model="staffLoginForm.pass">
<label class="checkbox">
<input type="checkbox" value="remember-me"> Ricordami
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="scripts/angular.js"></script>
<script type="application/javascript"></script>
<script src="scripts/login-controller.js"></script>
<script src="scripts/rest-services.js"></script>
</body></html>
I hope that somebody can help me
For factory file rest-services.js,change:
var app = angular.module("StaffLogin", []);
to
`var app = angular.module("StaffLogin");`
app.factory("restService", function($http) {
// code
});
You can't add $scope as dependency in Factory/services.
Hi Guys I need to change the existing profile name in settings page.
1. First Name must be displayed in Username: {{name}}
2. I have given button to show dialog box to change name, when clicked save the name must be changed and displayed in the Username:{{name}} That is all i needed.. I need code like below, This code is just a example..
var app = angular.module('AngularApp', ['ngMaterial']);
app.controller('SettingCtrl', ['$scope', '$mdDialog',
function($scope, $mdDialog) {
$scope.name = "test";
$scope.ChangeName = function(ev) {
$mdDialog.show({
controller: SetDialogController,
template: '<md-dialog aria-label="Add insert" md-theme="dialogtheme"><md-content>' +
'<form name="ChangeName"><div layout layout-sm="column"><md-input-container flex>' +
'<label>Client Name</label><input ng-model="newname" placeholder="New Name">' +
'</md-input-container><div></form> </md-content>' +
'<div class="md-dialog-actions" layout="row"> <span flex></span>' +
'<md-button ng-click="cancel()"> Cancel </md-button>' +
'<md-button ng-click="saveClient()" class="md-warn"> Save </md-button>' +
'</div></md-dialog>',
targetEvent: ev,
clickOutsideToClose: true
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
}
]);
function SetDialogController($scope, $mdDialog) {
$scope.saveClient = function() {}
$scope.cancel = function() {
$mdDialog.cancel();
};
};
<!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>ViewSalesVisit</title>
<!-- <link href="css/style.css" rel="stylesheet"> -->
<link href="js/angular-material.min.css" rel="stylesheet">
<!-- cordova script (this will be a 404 during development) -->
<!-- <script src="cordova.js"></script> -->
<script src="js/angular.min.js"></script>
<script src="js/angular-material.min.js"></script>
<script src="js/angular-aria.min.js"></script>
<script src="js/angular-animate.min.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="AngularApp" ng-controller="SettingCtrl">
<div>
<md-content md-scroll-y>
<md-toolbar class="md-toolbar-tools" layout-align="center">
<h3>Settings</h3>
</md-toolbar>
<div>
<h1>Username: {{name}}</h1>
<md-button class="md-primary md-raised" ng-click="ChangeName($event)" flex="100" flex-gt-md="auto">
Change Username
</md-button>
</div>
</md-content>
</div>
</body>
</html>
Thank you in advance guys..
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);
});
}
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;
};
On the HTML I have an overlay div to show a loading progress which uses the directive ng-show="showLoading". On the template ng-click I call the controller searchRequest method. This method updates showLoading to true just before making the http request.
If I do it this way the loading doesn't show, if I use the $scope.$apply to update the variable then I got the $apply already in progress error message. What is going on? How should I do this?
This is the 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>
<script src="js/angular-route.js" ></script>
<!-- your app's js -->
<script src="js/searchController.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="myApp" ng-init="showLoading = false">
<div id="overlay" ng-show="showLoading">
<img id="loading" src="img/ajax-spinner.gif" />
</div>
<div ng-view></div>
</body>
</html>
The template:
<div ng-controller="searchController as searchController">
<ion-header-bar class="bar-stable">
<h1 class="title">Movie Searcher</h1>
</ion-header-bar>
<ion-content>
<label class="item item-input">
<span class="input-label">Title</span>
<input style="border-style: solid;border-width: 1px;" type="text" ng-model="searchController.searchString" required>
</label>
<button class="btn" ng-click="searchController.search()">Search</button>
{{response}}
</ion-content>
</div>
And the controller:
this.searchRequest = function(url) {
$scope.showLoading = true;
$http.get(url).success(function(data) {
$scope.showLoading = false;
//console.log("Success: " + JSON.stringify(data));
$scope.response = JSON.stringify(data);
for (i=0; i<data.length; i++) {
var movie = data[i];
//console.log("Movie: " + movie);
var genres = '';
for (j=0; j<movie.genres.length; j++) {
genres += movie.genres[j];
if (j < movie.genres.length - 1) {
genres += ', ';
}
}
console.log("Title: " + movie.title);
console.log("Plot: " + movie.simplePlot);
console.log("genres: " + genres);
}
})
.error(function(data, status, headers, config) {
$scope.showLoading = false;
$scope.response = "Error: " + status;
})};
Your Overlay div does not have the data context of the right controller.
When you specify the ng-controller directive, you are telling angular to use that specific controller as its current scope.
<div ng-controller="searchController as searchController">
Whereas for your body section here, you did not specify the right controller. So, angular doesn't know where showloading property is coming from.
<body ng-app="myApp" ng-init="showLoading = false">
<div id="overlay" ng-show="showLoading">
<img id="loading" src="img/ajax-spinner.gif" />
</div>
<div ng-view></div>
</body>
Either move the overlay div into the div which has the controller as context or try using $rootScope instead.
Probably the easiest way to force a digest cycle without having to worry about the phase is to wrap the var change call inside a $timeout function:
$timeout(function() {
$scope.showLoading = true;
}, 0);
$http.get(url).success(function(data) {
...
Of course, don't forget to inject $timeout as a dependency in your controller.