how to get language of device with cordova angularjs? - angularjs

i want to include the navigator.globalization so i use this tutorial enter link description here
this code:
.run(function($ionicPlatform, $translate) {
$ionicPlatform.ready(function() {
if(typeof navigator.globalization !== "undefined") {
navigator.globalization.getPreferredLanguage(function(language) {
$translate.use((language.value).split("-")[0]).then(function(data) {
alert("SUCCESS -> " + data);
}, function(error) {
alert("ERROR -> " + error);
});
}, null);
}
});
my problem ,this code the alert is not displayed

You have it just with
window.navigator.userLanguage || window.navigator.language;

First check the result of
if(typeof navigator.globalization !== "undefined") {
If its false, the rest of the code will be skipped, because you dont have the plugin.
To get the plugin:
cordova plugin add cordova-plugin-globalization

Related

If loop is not working in AngularJS function

I am new to ionic therefore to cordova so in my controllers .js i am having a function defined as :
$scope.deleteFingerPrint = function() {
$scope.disableFingerPrint = true;
ss.remove(
function(key) {
console.log('Removed ' + key);
},
function(error) {
console.log('Error, ' + error);
},
'token');
localStorage.removeItem('isFingerPrintRequired');
localStorage.removeItem('hasEnrolledFingerprints');
isFromIosUserValidation = false;
$scope.deletePopup.close();
$ionicSideMenuDelegate.toggleLeft();
}
The code works fine but if i try to modify it like this:
$scope.deleteFingerPrint = function() {
$scope.disableFingerPrint = true;
ss.remove(
function(key) {
console.log('Removed ' + key);
},
function(error) {
console.log('Error, ' + error);
},
'token');
localStorage.removeItem('isFingerPrintRequired');
localStorage.removeItem('hasEnrolledFingerprints');
if (isIOS == true) {
isFromIosUserValidation = false;
}
$scope.deletePopup.close();
$ionicSideMenuDelegate.toggleLeft();
}
The popup comes but $scope.deletePopup.close(); doesnot works and the popup remains as it is.
What is the issue and why it is not getting closed. I have mentioned isIOS and isFromIosUserValidation globally.
Where did you define your isIOS variable, maybe the condition is not working so it give error. Please write code properly to understand the problem.

Angular: how to build a directive to watch a text field

Hello it's recently when I started using directives in my angular app.
I am building a text search, so what am trying to do is to have a text field and watch it to call the search server whenever user types into the text field.
Here is the directive I've built for this:
angular.module('myApp.directives')
.directive('autoComplete', function($resource, API_URL) {
var url = API_URL + 'api/search';
function link(scope, element, attrs) {
scope.$watch(attrs.autoComplete, function(value) {
if(value === null || value === "" ){
return;
}
$resource(url)
.get(function(products) {
// $scope.items = products;
console.log(products);
}, function(response) {
console.log(response);
});
});
} // Function link
return {
link: link
};
});
This the text field used to write the text for search:
<input type="text" placeholder="Search" ng-model="keyword" auto-complete>
The problem is the search endPoint is only called once when I browse to the view even without type anything in the search field also the watcher don't working call isn't made to the search server when I type in the search field.
I tired another way since I'm not familiar with directives yet but I got the same behaviour:
$scope.keyword = null;
$scope.$watch(function() { return $scope.keyword; }, function (newVal, oldVal) {
if (newVal !== "" || newVal !== null) {
$resource(url)
.get(function(products) {
console.log(products);
}, function(response) {
console.log(response);
});
} else {
return;
}//else
});
You need to watch 'ngModel' attribute instead attribute 'autoComplete'

Change template after login

I'm trying to change the page after authentication but nothing happens unless I click again at the login button.
Here is the code :
myApp.controller('AuthController', ['$scope','$location', function($scope,$location) {
// (1) $location.path('/produtos');
$scope.email = '';
$scope.pass = '';
$scope.submit = function() {
var ref = new Firebase("https://myfirebasedb.firebaseio.com/");
ref.authWithPassword({
email : $scope.email,
password : $scope.pass
}, function(error, authData) {
if (error) {
console.log("Login failed !", error);
} else {
console.log("Login ok ! "); // (2)
$location.path('/produtos');
}
});
};
}]);
Below are the observations -
The commented instruction at (1) works ok
The message at (2) is correctly printed at the console
Thank you in advance.
Looks like something interrupts location change. Try setTimeout(function(){$location.path('/produtos');}, 0); - that helps in such situations.

Pass parameter from controller to services in angularjs

How can i have one service or factory receiving two parameters from many controllers?
One parameter for the url, other for the file name to be stored on the filesystem.
I will have many controllers using this service, each passing his own url and filenames that reads the url and generate a pdf.
I will always store the last downloaded pdf providing an "open last pdf" button, that will use the name parameter.
I will have a "generate new pdf" button coming from the url.
I do follow this tutorial https://blog.nraboy.com/2014/09/manage-files-in-android-and-ios-using-ionicframework/ and everything works fine.
I am using cordova file-transfer and inappbrowser cordova plugins
These sections will receive the parameters :
dirEntry.getFile("pdf-number-1.pdf",
ft.download(encodeURI("http://www.someservice.com"),p,
My attempt always trigger the message unknow pdfService provider
Wich concepts of angular i am missing ? How can i fix it ?
In services.js i have :
.service('pdfService', function($scope, $ionicLoading){
if( window.cordova && window.cordova.InAppBrowser ){
window.open = window.cordova.InAppBrowser.open;
console.log("InAppBrowser available");
} else {
console.log("InAppBrowser not available");
}
this.download = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory("ExampleProject",{create: true},
function(dirEntry) {
dirEntry.getFile(
"pdf-number-1.pdf",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI("http://www.someservice.com"),
p,
function(entry) {
$ionicLoading.hide();
$scope.imgFile = entry.toURL();
},
function(error) {
$ionicLoading.hide();
alert("Download Error Source -> " + error.source);
},
false,
null
);
},
function() {
$ionicLoading.hide();
console.log("Get file failed");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Request for filesystem failed");
});
}
this.load = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory(
"ExampleProject",
{
create: false
},
function(dirEntry) {
dirEntry.getFile(
"pdf-number-1.pdf",
{
create: false,
exclusive: false
},
function gotFileEntry(fe) {
$ionicLoading.hide();
$scope.imgFile = fe.toURL();
alert(fe.toURL());
window.open(fe.toURL(), '_system', 'location=no,toolbar=yes,closebuttoncaption=Close PDF,enableViewportScale=yes');
},
function(error) {
$ionicLoading.hide();
console.log("Error getting file");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Error requesting filesystem");
});
}
});
And in the controller :
.controller('SomeCtrl', function($scope, $ionicPopup, pdfService) {
...
pdfService.download = function(url) {
console.log('pdfService download');
}
pdfService.load = function() {
console.log('pdfService load');
}
You will need to inject the service to your controllers and call a function with the two params you want as your arguments.
eg.
.service('pdfService', function(){
var lastUrl;
var lastFileName
return {
createPdf(url, fileName){
//do processing
lastUrl = url;
lastFileName = fileName
},
loadLastPdf(){
//use lastUrl and lastFileName
}
}
}
and in your controller:
.controller('SomeCtrl', function(pdfService) {
pdfService.createPdf('http://example.com', 'file.pdf');
// or pdfService.loadLastPdf();
}
That being said, the error you are reporting means that the DI is unable to find a service with the name pdfService to inject to your controller. This might be because you forgot to include the service.js file to your html as a script tag (if you are doing it like that) or you forgot to add it as a dependency using require (if you are using sth like browserify) or maybe if you are minifying your code since you are not using the minsafe syntax

ngCordova get GCM regid inside a controller

I'm having troubles trying to register my GCM regid with ngCordova and $cordovaPush.
I can't manage to retrieve my regid inside my controller to send it to my API via $http:
var gcmToken;
gcmNotificationHandler = function(e) {
if (e.event === "registered") {
gcmToken = e.regid;
console.log(gcmToken);
}
};
var aTonAvis = angular.module('aTonAvis', ['ngCordova']);
aTonAvis.value('serverUrl', "http://atonavis.local/");
aTonAvis.controller('RegisterCtrl', function($scope, $cordovaPush,
$cordovaDevice, $http, serverUrl) {
var gcmConfig = {
"senderID": "00000000000"
};
var iosConfig = {
"badge": "true",
"sound": "true",
"alert": "true",
};
gcmConfig.ecb = "gcmNotificationHandler";
iosConfig.ecb = "iosNotificationHandler";
var configHandler = function() {
if ($cordovaDevice.getPlatform().toLowerCase() ===
'android' || $cordovaDevice.getPlatform() ===
'amazon-fireos') {
return gcmConfig;
} else {
return iosConfig;
}
};
this.registered = false;
document.addEventListener("deviceready", function onDeviceReady() {
$cordovaPush.register(configHandler()).then(function(
result) {
console.log("Inside register " + gcmToken);
var pushToken;
if ($cordovaDevice.getPlatform().toLowerCase() ===
'ios') pushToken = result;
else pushToken = gcmToken;
$http.post(serverUrl + 'api/setdevice', {
token: pushToken,
device: $cordovaDevice.getPlatform(),
version: $cordovaDevice.getVersion(),
model: $cordovaDevice.getModel()
}).success(function(data, status,
headers, config) {
this.registered = true;
});
}, function(err) {
console.log("Registering Error : " + err);
});
});
});
The .then function is fired before the gcmNotificationHandler so my gcmToken is undefined, and here's what I get in my logs :
Inside register : undefined app.js:41
APA91bEzVUk3T1T6WpIsEHOq43hCh_pZeBPjRDPSPxV2j6VjVW-KcUepbmf6snaCiqGvYp3H_XYHIXQdbVtvMF3t-NtoZJaJzV9FkNtUlutuWYs5XPAZ-H1ixQnAyhTO6fAPDMn7Ef5f5HgBR9fgWpmXc0u_xBM4yKvoXCnVXEG18IZV2hvY app.js:6
I don't know what I'm doing wrong here, can anybody help ?
You need to install these two cordova plugins before run the app.
Device cordova plugin: https://github.com/apache/cordova-plugin-device
cordova plugin add https://github.com/apache/cordova-plugin-device
Console cordova plugin: https://github.com/apache/cordova-plugin-console
cordova plugin add https://github.com/apache/cordova-plugin-console
http://blog.revivalx.com/2014/11/14/implement-push-notifications-for-android-and-ios-phonegap-part-3/
Here is my code that uses ngCordova with PushPlugin. The regid comes in the same callback for event 'pushNotificationReceived' for android. Here is the code I use within the callback for that event to receive the regid from GCM:
Checking for (notification.event === 'registered') is the most important.
$rootScope.$on('pushNotificationReceived', function(event, notification) {
//console.log("result: " + JSON.stringify(event));
console.log("result: " + JSON.stringify(notification));
console.log('Success: Inside the push notification received callback with this payload JSON' + notification);
if(( platform == 'android' || platform == 'Android' ) && notification.regid && (notification.event === 'registered'))
{
var googDevToken = notification.regid;
console.log(googDevToken);
}
});

Resources