How can I use ng-if with ionicPopup - angularjs

I'm trying to do so, when I click on the send button a popup appears, where if the person enters the correct message it goes to the next screen if not it stays on the screen that is.
my code :
my controller.js
.controller('loginController', function($scope, $stateParams, $ionicPopup, $ionicHistory, $state) {
$scope.Enviar = function(){
var confirmPopup = $ionicPopup.prompt({
title: 'Login',
template: 'Pergunta: Digite a P∴S∴ do AP∴?',
inputType: 'text',
inputPlaceholder: 'Digite a senha',
ng-model="login"
});
confirmPopup.then(function(res) {
if(res) {
$state.go('app.home');
} else {
console.log('teste');
$state.go('login');
}
})
}
})
my login.html
<ion-view view-title="login">
<ion-content class="login-principal" scroll="true">
<div class="login-imagem">
<img class="full-image" ng-src="img/GOMB.jpg">
</div>
<div>
<ion-list class="list-inset">
<ion-item class="item-input">
<i class="icon ion-ios-email-outline placeholder-icon"></i>
<input type="text" placeholder="E-mail">
</ion-item>
<ion-item class="item-input">
<i class="icon ion-ios-locked-outline placeholder-icon"></i>
<input type="text" placeholder="Senha">
</ion-item>
</ion-list>
<div class="row login">
<div class = "col col-50" >
<a class="button button-block button-dark" ui-sref="app.cadastroUsuario">Criar conta</a>
</div>
<div class = "col col-50" >
<a class="button button-block button-dark" ng-click="Enviar()">Entrar</a>
</div>
</div>
</div>
</ion-content>
</ion-view>
My question is how to use ng-model and ng-if with ionicPopup?

Instead of $ionicPopup.prompt you can just make use of $ionicPopup.show and in template property of its object write whatever the template you want (with ng-model & ng-if). You can also have buttons with their customizable text as well as particular action onTap (like returning model value of input fields inside popup). So, you can have following function to call popup:
$scope.showPopup = function() {
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<input type="password" ng-if="isNotConnected"
ng-model="data.wifi" placeholder="Enter Password">',
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;
}
}
},
]
});
myPopup.then(function(res) {
console.log('Tapped!', res);
});
};
Check out this codepen: https://codepen.io/anon/pen/wqwzPE

$scope.Enviar = function(){
var obj = new String("boa");
$ionicHistory.nextViewOptions({
disableBack : true
})
var confirmPopup = $ionicPopup.prompt({
title: 'Login',
template: 'Pergunta: Digite a?',
inputType: 'text',
inputPlaceholder: 'Digite em minusculo'
});
confirmPopup.then(function(res) {
if(res == obj) {
$state.go('app.home');
console.log(res);
} else {
//console.log('teste');
$state.go('login');
//console.log(res);
}
})
}

Related

How to clear input field on button click in Ionic 1

I am new to Ionic 1. The problem is click on Submit button the input fields doesn't clear. On button click after posting data to server it reloads the same page but with already entered fields.
html
<div style="margin-left: 20px;margin-right: 20px;margin-top: 55px;">
<div class = "list">
<label class = "item item-input item-stacked-label">
<!-- <span class = "input-label">Name</span> -->
<input type = "text" placeholder = "Name" required ng-model="name" clearInput="true"/>
</label>
</div>
<div class = "list">
<label class = "item item-input item-stacked-label">
<!-- <span class = "input-label">Mobile Number</span> -->
<input type = "tel"maxlength="10" clearInput="true" placeholder = "Mobile No." pattern="[1-9]{1}[0-9]{9}" required ng-model="mobile" />
</label>
</div>
<div class="padding text-right" style="margin-top: -12px;">
<button class="button button-positive " ng-click="enter(name,mobile)" style="width: 100%;">
Submit
</button>
</div>
</div>
js
$scope.enter = function (name,mobile) {
if (name == null) {
var alertPopup = $ionicPopup.alert({
template: 'Please Enter Name!'
});
} else if (mobile == null) {
var alertPopup = $ionicPopup.alert({
template: 'Please Enter Mobile Number!'
});
}
else {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner><p>Loading...</p>'
});
var link = 'http://mountsystem/mobileapi/coreapi.php';
var datasend = $.param({
request_code: 'demo_attendance',
batch_id:$stateParams.batchId,
mobile_no: mobile,
student_name: name,
franchise_id: $scope.userDetails.franchise_id,
entered_by:$scope.userDetails.employee_id
});
console.log(datasend);
$http.post(link, datasend, config)
.success(function (response) {
$ionicLoading.hide();
console.log(response);
if (response.response_code == 'STATUS_OK') {
$scope.list = response;
console.log($scope.list);
var alertPopup = $ionicPopup.alert({
title: 'Hurrayy',
content: 'Successfully Submitted !'
})
} else {
var alertPopup = $ionicPopup.alert({
title: 'Error!',
template: response.msg
});
}
}).error(function (response) {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'ServerError!',
template: 'ServerError' + response
});
});
}}
I just want as soon as I click submit button both input fields (username and mobile number) will be clear so that I again entered new details.
Try to set the name and telephone variables to "" in your .js file. It will clear the fields in the front.
Also why are you still using Ionic 1. I recommend moving to Ionic 3, waiting the fourth version to be really stable.
Change ng-model variable with below code
<div style="margin-left: 20px;margin-right: 20px;margin-top: 55px;">
<div class = "list">
<label class = "item item-input item-stacked-label">
<!-- <span class = "input-label">Name</span> -->
<input type = "text" placeholder = "Name" required ng-model="data.name" clearInput="true"/>
</label>
</div>
<div class = "list">
<label class = "item item-input item-stacked-label">
<!-- <span class = "input-label">Mobile Number</span> -->
<input type = "tel"maxlength="10" clearInput="true" placeholder = "Mobile No." pattern="[1-9]{1}[0-9]{9}" required ng-model="data.mobile" />
</label>
</div>
<div class="padding text-right" style="margin-top: -12px;">
<button class="button button-positive " ng-click="enter(data.name,data.mobile)" style="width: 100%;">
Submit
</button>
</div>
</div>
$scope.data = {};
$scope.enter = function (name,mobile) {
if (name == null) {
var alertPopup = $ionicPopup.alert({
template: 'Please Enter Name!'
});
} else if (mobile == null) {
var alertPopup = $ionicPopup.alert({
template: 'Please Enter Mobile Number!'
});
}
else {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner><p>Loading...</p>'
});
var link = 'http://mountsystem/mobileapi/coreapi.php';
var datasend = $.param({
request_code: 'demo_attendance',
batch_id:$stateParams.batchId,
mobile_no: mobile,
student_name: name,
franchise_id: $scope.userDetails.franchise_id,
entered_by:$scope.userDetails.employee_id
});
console.log(datasend);
$http.post(link, datasend, config)
.success(function (response) {
$ionicLoading.hide();
console.log(response);
if (response.response_code == 'STATUS_OK') {
$scope.list = response;
console.log($scope.list);
$scope.data.mobile = '';
$scope.data.name = '';
var alertPopup = $ionicPopup.alert({
title: 'Hurrayy',
content: 'Successfully Submitted !'
})
} else {
var alertPopup = $ionicPopup.alert({
title: 'Error!',
template: response.msg
});
}
}).error(function (response) {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'ServerError!',
template: 'ServerError' + response
});
});
}}
I am quite amazed with the solution but this solution worked for me, the problem was instead of setting a value directly inside $scope object, I was supposed to put it within any object of $scope object like this
<input type="text" placeholder="Enter new todo" ng-model="data.newtodo"> first change model of input field to like this
and in my controller, on top
$scope.data = {};
and after success callback
$scope.data.newtodo = "";

ion-slides, each overlap with ng-repeat

I'm real newbie in ionic, html, angular and java script. I have an app that take some JSON data and display it with ng-repeat.
But when I tried to switch to the next slide, it overlap. and I have an $interval that refresh JSON each 5 sec, it reset to the first slide also.
here html:
<ion-view title="home">
<ion-content ng-controller="temperatureCtrl">
<div ng-init="init()"></div>
<ion-slides options="options" slider="data.slider" >
<ion-slide-page ng-repeat="channel in channels">
<div class="list">
<h2><center>canal# {{channel.canal}}</center></h2>
<br/>
<center>
<button class="button button-stable" ng-click="switchChannel(channel, channel.canal)" ng-model="channel.status">
{{channel.status}}
</button>
</center>
<div class="list">
<label class="item item-input">
<input type="text" style="text-align:center;" placeholder="Channel name" ng-model="channel.name" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
</label>
</div>
<h4><center>
<span class="Ainput" ><h3>{{channel.temperature}}ºC</h3></span>
</center></h4>
<h3><center>Setpoint= {{channel.setPoint}}</center></h3><br>
<div class="item range range-positive">
<i class="icon ion-minus-round"></i>
<input type="range" name="setpoint" min="5" max="30" step="0.5" value="33" ng-model="channel.setPoint" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
<i class="icon ion-plus-round"></i>
</div>
<centrer>
<button class="button button-dark button-block padding " ng-click="channelsClk(channel, channel.setPoint)">ok</button>
</centrer>
<h3>
<span class="permRun">{{channel.permission}}</span>
</h3>
<h3>
<span class="AoutputChannel">{{channel.percentOut}}%</span>
</h3>
</ion-slide-page>
</ion-slides>
</ion-content>
and the controler:
main.controller("temperatureCtrl", ["$scope", "$interval", "ArduinoService", function($scope, $interval, service) {
var autoRefresh;
$scope.channels = [];
$scope.options = {
loop: false,
effect: 'fade',
speed: 500,
}
$scope.data = {};
$scope.$watch('data.slider', function(nv, ov) {
$scope.slider = $scope.data.slider;
})
function startRefresh(){
autoRefresh = $interval(function() {
updateAjax();
}, 5000);
}
function updateAjax() {
service.getChannels(function(err, result) {//get json data
if (err) {
return alert(err);
}
// puis les mets dans le scope
$scope.channels = result.channels;
})
};
$scope.init = function() { //on load page first get data
updateAjax();
startRefresh()
}
$scope.switchChannel = function($scope, channel) { // change name function
var switchCh = {canal : $scope.canal, status : $scope.status}
service.switchChannel(switchCh, function() {
});
updateAjax();
};
$scope.channelsClk = function($scope, channel) {
var chanObj = {setPoint : $scope.setPoint, name : $scope.name, canal : $scope.canal
};
service.putChannels(chanObj, function() {
});
}
$scope.stopRefresh = function() { //ng-mousedown
$interval.cancel(autoRefresh);
};
$scope.restartRefresh = function() {
startRefresh();
};
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopRefresh();
});
}]);
remove option fade solve the problem.
$scope.options = {
loop: false,
//effect: 'fade', /* <-- */
speed: 500,
}

Ionic List is Not Updating with new data

I have a simple Ionic app which consists of a list like this:
<ion-list ng-controller="MainController">
<ion-item ng-repeat="task in tasks">
{{task.title}}
</ion-item>
</ion-list>
In the MainController I add a new item to the tasks collection:
.controller('MainController',function($scope,$ionicPopup){
$scope.tasks = [{title:"Clean dishes"},{title :"File Tax"},{title :"Take Pictures"}];
$scope.task = new Object();
$scope.showAddNewTaskDialog = function() {
var popup = $ionicPopup.show({
template:'<label class="item item-input"> <input ng-model="task.title" type="text" placeholder="Enter Task"/></label>',
title: 'New Task',
scope: $scope,
buttons :[
{ text :'Cancel'},
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function(e) {
$scope.tasks.push({ title :'new entry'});
}
}
]
});
}
})
But even though I am adding a new item in the tasks the list never refreshes.

How to clear form after post?

I'm creating an app using Ionic. After send values of form I want to clear form but I can't do this.
How could I do this ?
form
<form name="Empresa">
<div class="list">
<label class="item item-input"
ng-class="{'has-errors':Empresa.nomeemp.$invalid, 'no-errors':Empresa.nomeemp.$valid}">
<input type="text"
placeholder="Nome"
name="nomeemp"
ng-model="Empresa.nome"
ng-required="true">
</label>
<div class="error-container"
ng-show="(Empresa.nomeemp.$dirty || !Empresa.nomeemp.$pristine)"
ng-messages="Empresa.nomeemp.$error">
<div ng-messages-include="templates/form-errors.html"></div>
</div>
</div>
<button type="button" class="button button-block button-energized"
ng-disabled="Empresa.$invalid" ng-click="addEmpresa(Empresa);">Cadastrar</button>
</form>
controller
$scope.addEmpresa = function(Empresa){
var _pathFile = document.getElementById("smallimage").src;
var _fileName = _pathFile.substr(_pathFile.lastIndexOf('/') + 1);
if(_fileName === 'no-image.png'){
$ionicLoading.show({ template: APP_MESSAGES.escolhaImagem, noBackdrop: true, duration: 2000 });
}else{
$ionicLoading.show();
EmpresaAPIService.addEmpresa(Empresa).then(function (data) {
$ionicLoading.hide();
var retorno = JSON.parse(data.response);
if(retorno.status === 0){
$ionicLoading.show({ template: retorno.msg, noBackdrop: true, duration: 2000 });
}
if(retorno.status === 1){
//clear form
delete Empresa;
Empresa.$setPristine();
Empresa.$setUntouched();
$ionicLoading.show({ template: retorno.msg, noBackdrop: true, duration: 2000 });
}
}, function (err) {
$ionicLoading.hide();
}, function (progress) {
// PROGRESS HANDLING GOES HERE
});
}
}
In your controller after you do your submission logic, set $scope.Empresa.noma = ''; as that's what is being bound to your form in your application.
edit: setPristine() should also work.

Button doesn't update with new inputDate from Ionic Date Picker

I need a date picker for my Ionic app. I am trying to use this one as it seems popular:
https://github.com/rajeshwarpatlolla/ionic-datepicker
I have tried to follow the tutorial, and it works well, but the date button doesn't update based on the date selection. How can I make it update?
My code is below.
This is my controller:
app.controller('EnterDatapointCtrl', function($scope, $state) {
$scope.datepickerObject = {
titleLabel: 'Title', //Optional
inputDate: new Date(), //Optional
callback: function (val) { //Mandatory
datePickerCallback(val);
}
};
var datePickerCallback = function (val) {
if (typeof(val) === 'undefined') {
console.log('No date selected');
} else {
console.log('Selected date is : ', val)
}
};
});
This is my template:
<ion-view view-title="New Sales">
<ion-content class="padding">
<ionic-datepicker input-obj="datepickerObject">
<button class="button button-block button-positive"> {{datepickerObject.inputDate | date:'dd - MMMM - yyyy'}}</button>
</ionic-datepicker>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Amount" ng-model="data.amount">
</label>
</div>
<button class="button button-block button-stable" ng-click="save()">Save</button>
</ion-content>
</ion-view>
I added a line to the callback. I didn't understand that I was supposed to modify the callback function.
$scope.datepickerObject.inputDate = val;
app.controller('EnterDatapointCtrl', function($scope, $state) {
$scope.datepickerObject = {
titleLabel: 'Title', //Optional
inputDate: new Date(), //Optional
callback: function (val) { //Mandatory
datePickerCallback(val);
}
};
var datePickerCallback = function (val) {
if (typeof(val) === 'undefined') {
console.log('No date selected');
} else {
console.log('Selected date is : ', val)
$scope.datepickerObject.inputDate = val;
}
};
$scope.save = function() {
$state.go('confirm-datapoint');
};
});

Resources