how to add localization in ionic popup - angularjs

i had completed ionic project. i would like to change lanaguages in this code. project title, place holder , button it had changed but popup was doesn't changed. i used this code in controller and language change file.
farmer-ctrl.js :
function showPopup () {
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="data.category">',
title: '{{"farmers_message" | translate}}', //'Enter CoconutType',
scope: $scope,
buttons: [
{ text: 'Cancel' },
{
text: '<b>{{"save_message" | translate}}</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.data.category) {
//don't allow the user to close unless he enters producttype
e.preventDefault();
} else {
$log.log('yes clicked: ', $scope.data.category);
addProductType();
return $scope.data.category;
}
}
},
]
});
myPopup.then(function (res) {
$log.log('Tapped!', res);
});
}

i had founded by adding translate.instant
function showPopup () {
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="data.category">',
// title: 'Enter CoconutType',
title: $translate.instant('{{"farmers_message" | translate}}'),
scope: $scope,
buttons: [
{ text: 'Cancel' },
{
text: $translate.instant('{{"save_message" | translate}}'),
type: 'button-positive',
onTap: function (e) {
if (!$scope.data.category) {
//don't allow the user to close unless he enters producttype
e.preventDefault();
} else {
$log.log('yes clicked: ', $scope.data.category);
addProductType();
return $scope.data.category;
}
}
},
]
});
myPopup.then(function (res) {
$log.log('Tapped!', res);
});
}

To add localization in popup you need something like this:
var alertPopup = $ionicPopup.alert({
title: $translate.instant('networkerror'),
template: '<div><p translate="onlinemessagepois"></p></div>'
});
where networkerror and onlinemessagepois exist in your local js files. (Example: "networkerror":"sometext","onlinemessagepois":"someothertext" )
Note: you have to inject $translate in your controller.

Related

cannot call function from within ionic popup

I am new to ionic.
I have a function in my controller. I want to call that function from another function which has ionic popup. but, the function call does not happen.
Here is the code
Function with ionic popup
$scope.show = function() {
var myPopup = $ionicPopup.show({
templateUrl: 'views/d.html',
cssClass: 'custom-ipopup',
title: 'Welcome to myapp',
subTitle: 'enter username.',
scope: $scope,
buttons: [
{ text: '<b>Cancel</b>' },
{
text: 'Test',
type: 'button-positive',
onTap: function(e) {
e.preventDefault();
scope.usernameCheck = usernameLookup();
console.log(scope.usernameCheck); //prints undefined
}
}
]
});
};
usernameLookup() function i am calling from $ioninPopup.show()'s onTap()
$scope.usernameLookup = function() {
console.log('inside usernameLookup()');
$scope.lookingDB = true;
$scope.unamePresent = 3;
$http({
method: 'GET',
url: $rootScope.cred.url + '/api',
params: {
}
}).success(function(d) {
$scope.lookingDB = false;
$scope.unamePresent = 1;
return $scope.unamePresent
}).error(function(d) {
$scope.lookingDB = false;
$scope.unamePresent = 2;
return $scope.unamePresent
});
};
Can someone tell me why is it not calling usernameLookup() function? Both these methods are in same controller.

How to split angularjs controller into chunks?

I am very new to AngularJs and hope I can get some help here. Below I have two controllers that are very similar. One is for editing an item and one for adding a new item. I would like to know how I can refactor this code in order to reuse most of this code for both controllers or simply use one controller for both. I originally tried to use one controller for both but the new item page wouldn't let me type anything into the fields. I supposed because there was no current model data like there is when editing.
Any help would be appreciated.
tplApp.controller('editController', function ($scope, $http, $routeParams){
$scope.template = {};
$scope.id = $routeParams.template_id;
$http.get(baseUrl+'templates/get_template/'+$scope.id).success(function(data) {
$scope.template = data;
});
$scope.bodyOptions = {
plugins: 'link image code',
toolbar: 'bold, italic, underline, alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
height: 300,
menubar: false,
statusbar: false,
setup: function(editor) {
editor.addButton('mybutton', {
type: 'menubutton',
text: 'Variables',
icon: false,
menu: [
{text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}},
{text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
{text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
{text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
]
});
}
};
$scope.saveTemplate = function() {
$http({
method : 'POST',
url : baseUrl+'templates/save',
data : $.param($scope.template),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
$scope.message = data.message;
if (data.success) {
console.log(data);
$scope.templates = data.templates;
}
});
};
});
tplApp.controller('addController', function ($scope, $http){
$scope.template = {};
$scope.bodyOptions = {
plugins: 'link image code',
toolbar: 'bold, italic, underline, alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
height: 300,
menubar: false,
statusbar: false,
setup: function(editor) {
editor.addButton('mybutton', {
type: 'menubutton',
text: 'Variables',
icon: false,
menu: [
{text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}},
{text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
{text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
{text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
]
});
}
};
$scope.saveTemplate = function() {
$http({
method : 'POST',
url : baseUrl+'templates/save',
data : $.param($scope.template),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
$scope.message = data.message;
if (data.success) {
console.log(data);
$scope.templates = data.templates;
}
});
};
});
What you want is a service: https://docs.angularjs.org/guide/services
"You can use services to organize and share code across your app"
Google it and/or look here in SO for more info.
Try these changes. You will need 2 services + 2 controllers (for saveTemplateService.js and buildBodyOptionsService.js ). The services will be injected to the controllers.
At the end,don't forget to add the src of each service in the template/html file.
I think it could be even more reduced (without the $http's success in the controllers) but since we are working with callbacks here, I'm not sure. Try it out ;).
It might not be fully functional because I don't have all your code. But debugging should solve it.
saveTemplateService.js:
app.factory('saveTemplateService', function ( baseUrl, $http ) {
return $http({
method : 'POST',
url : baseUrl+'templates/save',
data : $.param($scope.template), //fix these (injecting them like baseUrl)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
});
buildBodyOptionsService.js:
app.factory('buildBodyOptionsService', function() {
return {
build: function ( editor ) { //maybe editor needs to be injected
var output = {
plugins: 'link image code',
toolbar: 'bold, italic, underline, alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
height: 300,
menubar: false,
statusbar: false,
setup: function(editor) {
editor.addButton('mybutton', {
type: 'menubutton',
text: 'Variables',
icon: false,
menu: [
{text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}}, // I dont like this functions here. There must be a better way to do this (ex: in a partial html with ng-click)
{text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
{text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
{text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
]
});
}
};
return output;
}
};
});
editController.js
tplApp.controller('editController', function ($scope, saveTemplateService, buildBodyOptionsService) {
$scope.template = {};
$scope.id = $routeParams.template_id;
$http.get(baseUrl+'templates/get_template/'+$scope.id)
.success(function(data) {
$scope.template = data;
});
// call 1st service
$scope.bodyOptions = buildBodyOptionsService.build( editor );
// call 2nd service
$scope.saveTemplate = saveTemplateService.success( function(data) {
$scope.message = data.message;
if (data.success) {
console.log(data); //use $log.info() instead
$scope.templates = data.templates;
}
});
});
addController.js
tplApp.controller('addController', function ($scope, saveTemplateService, buildBodyOptionsService) {
$scope.template = {};
// call 1st service
$scope.bodyOptions = buildBodyOptionsService.build( editor );
// call 2nd service
$scope.saveTemplate = saveTemplateService.success( function(data) {
$scope.message = data.message;
if (data.success) {
console.log(data); //use $log.info() instead
$scope.templates = data.templates;
}
});
});
Check these links for more info:
custom services in Angular (really well explained): https://youtu.be/rlx1cf7qM0E?list=PL6n9fhu94yhWKHkcL7RJmmXyxkuFB3KSl
promises in services: AngularJS: Performing $http request inside custom service and returning data
(relevant) Angular $http difference between .success() and .then()
I would probably put everything in a single service (templateService). I'm not sure if the bodyOption belongs there but for now I would just put it there. Then I would move the load/save template function to the service.
You could probably do more, for instance, your might set the $scope.templateService = templateService and in your html use templateService.bodyOptions/templates directly.
Also, you could probably move the save.success from the controller to the service aswell.
tplApp.service('templateService', function($http, $routeParams) {
var self = this;
this.template = {};
this.loadTemplate = function() {
$http.get(baseUrl+'templates/get_template/' + $routeParams.template_id)
.success(function(data) {
self.template = data;
});
};
this.saveTemplate = function() {
return $http({
method: 'POST',
url: baseUrl + 'templates/save',
data: $.param(self.template),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
};
this.bodyOptions = {
plugins: 'link image code',
toolbar: 'bold, italic, underline, alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
height: 300,
menubar: false,
statusbar: false,
setup: function(editor) {
editor.addButton('mybutton', {
type: 'menubutton',
text: 'Variables',
icon: false,
menu: [
{text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}},
{text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
{text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
{text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
]
});
}
};
});
tplApp.controller('editAndAddController', function ($scope, templateService){
$scope.template = templateService.template;
$scope.bodyOptions = templateService.bodyOptions;
if(edit) {
templateService.loadTemplate();
}
$scope.saveTemplate = function() {
templateService.saveTemplate()
.success(function(data) {
$scope.message = data.message;
if (data.success) {
console.log(data);
$scope.templates = data.templates;
}
});
};
});
Ideally your controller would probably look like this:
tplApp.controller('editAndAddController', function ($scope, templateService){
$scope.templateService = templateService;
if(edit) {
templateService.loadTemplate();
}
});
Heads up! This is just example, code is not tested!

Custom Ionic Framework Popup

I have an IONIC popup, See image below in the link.
I have an issue when i click on the buttons Arrange Coupon, It redirect me to the next screen. It is fine.But the popup doesn't hide. Please help me.
Thanks.
http://awesomescreenshot.com/0e55lzsl39
var myPopup;
$scope.showPopup = function() {
myPopup = $ionicPopup.show({
template: '<a class="button button-block button-energized" href="#/redeem">Arrange Coupon</a> <a class="button button-block button-balanced">Add Coupon</a> ',
title: 'Coupon Management',
buttons: [{
text: '<b>OK</b>',
type: 'button button-small button-positive',
onTap: function(e) {
}
}, ]
});
myPopup.then(function(res) {
if (res) {
console.log(res);
}
else{
alert('here');
}
});
};
Looks like you forgot to add the image. However, The Ionic Popup service allows programmatically creating, showing and closing popup.
If you have a popup defined like this,
var myPopup = $ionicPopup.show({
template: '<input type="password" ng-model="data.wifi">',
title: 'Enter Wi-Fi Password',
subTitle: 'Please use normal things',
scope: $scope,
buttons: [
{ text: 'Cancel' },
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function(e) {
if (!$scope.data.wifi) {
//don't allow the user to close unless he enters wifi password
e.preventDefault();
} else {
return $scope.data.wifi;
}
}
}
]
});
You can close it like this
myPopup.close();

Ionic close IonicPopup when button makes an Ajax call

Am new to both angular and ionic. I have a popup in my page where i show user a input field to enter the OTP and a submit button. When i click on the submit button, I make an Ajax call to check if the OTP is valid.
But am not able to close the popup with .close method. Please help
var OTPPopup = $ionicPopup.show({
title: 'OTP VERIFICATION',
templateUrl: 'templates/login/otp.html',
scope: $scope,
buttons : [{
text: 'Confirm OTP',
type: 'button-assertive',
onTap : function(e) {
e.preventDefault();
var validateResponse = validateOTP();
validateResponse.then(function(response){
console.log('success', response);
return response;
});
}
}]
}).then(function(result){
console.log('Tapped', result);
OTPPopup.close();
});
And below is the function validateOTP
function validateOTP() {
var requestObj = {
authentication: {
email_id: $scope.loginForm.email,
security_code: $scope.OTP
}
};
return $q(function(resolve, reject) {
activateUser(requestObj, function(response){
if(response.error == null && response.data.isSuccess) {
console.log('validate correct');
resolve(response);
}
}, function(response){
return 'error';
});
});
}
activateUser is my service which makes the ajax call. Please let me know how can i acheive this.
console.log('success', response) is being printed inside the .then but after returning something from the onTap , the promise of the popup is not being called.
Ended up solving it myself.
This solution would work only if you have exactly one ionicPopup on your page. I just wrote this line of code to do the trick
$ionicPopup._popupStack[0].responseDeferred.resolve();
This automatically closes the popup. The whole code is more simpler now with normal Ajax without any q promises.
var OTPPopup = $ionicPopup.show({
title: 'OTP VERIFICATION',
templateUrl: 'templates/login/otp.html',
scope: $scope,
buttons : [{
text: 'Confirm OTP',
type: 'button-assertive',
onTap : function(e) {
// e.preventDefault() will stop the popup from closing when tapped.
e.preventDefault();
validateOTP();
}
}]
});
and in the next function
function validateOTP() {
var requestObj = {
authentication: {
email_id: $scope.loginForm.email,
security_code: $scope.loginForm.OTP
}
};
activateUser(requestObj, function(response){
if(response.error == null && response.data.isSuccess) {
localStorage.setLocalstorage = response.data.user[0];
$ionicPopup._popupStack[0].responseDeferred.resolve();
$state.go('dashboard.classified');
}
}, function(response){
});
}
you don't need call e.preventDefault();
you just only return the validateOTP promise
ionicPopup will waiting the promise then close popup
var OTPPopup = $ionicPopup.show({
title: 'OTP VERIFICATION',
template: 'templates/login/otp.html',
scope: $scope,
buttons : [{
text: 'Confirm OTP',
type: 'button-assertive',
onTap : function() {
return validateOTP();
}
}]
}).then(function(result){
console.log('closed', result); // result is the activateUser resolve response
});

how to close pop up screen when click out side in screen

I make one pop up screen I open pop up screen on button screen .I want to hide pop up screen when I click outside the screen can is this possible ?
code
http://codepen.io/anon/pen/KpLgpm
angular.module('ionic.example', ['ionic'])
.controller('PopupCtrl', function($scope, $timeout, $q, $ionicPopup) {
$scope.showPopup = function() {
$scope.data = {}
$scope.setDefault = function () {
console.log('Default set', arguments);
$scope.$onClose({ test: 'hello' });
};
$scope.btns = [
{
label: "Hi",
value: "hi"
},
{
label: "Hello",
value: "hello"
}
];
$ionicPopup.show({
template: '',
title: 'Pick a default value',
scope: $scope,
buttons: [
{
text: 'Awesome',
onTap: function(e) { return 'awesome'; }
},
{ text: 'Cool', onTap: function(e) { return 'cool'; } },
{ text: 'Cooler', onTap: function(e) { return 'cooler'; } },
{ text: 'Stuff', onTap: function(e) { return 'stuff'; } }
]
}).then(function(res) {
console.log('Tapped!', res);
}, function(err) {
console.log('Err:', err);
}, function(msg) {
console.log('message:', msg);
});
};
});
angular.element( $window ).on( "click", function( event ) {
if( angular.element( "#popdiv" ).has( event.srcElement || event.target ).length === 0 ) {
// hide popup
}} );
I've found a solution, called "ionic-close-popup".
Install this in your project, add in your index.html, inject in the controller, and register the popup:
https://libraries.io/bower/ionic-close-popup
You can create a directive with below code
angular.module("testapp").directive('clickAnywhereButHere', ["$document", function ($document) {
//click-any-where-but-here
return {
restrict: 'A',
link: function (scope, elem, attr, ctrl) {
var elemClickHandler = function (e) {
e.stopPropagation();
};
var docClickHandler = function () {
scope.$apply(attr.clickAnywhereButHere);
};
elem.on('click', elemClickHandler);
$document.on('click', docClickHandler);
// teardown the event handlers when the scope is destroyed.
scope.$on('$destroy', function () {
elem.off('click', elemClickHandler);
$document.off('click', docClickHandler);
});
}
};
Then in your html element
<div class="mypopup" click-anywhere-but-here="function(){ alert('click out popup event')}"></div>

Resources