How to clear input field on button click in Ionic 1 - angularjs

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

Related

Angular ui-calendar auto refresh on form submission

i am using angular ui-calendar for displaying a series of leaves.The data for this is fed from the REST services.I can add a leave to the database also.The problem is that when i add a leave detail to the database it does not automatically reflect in the calendar.If i refresh the page the data will be reflected. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.Following is my code
My controller
app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
$scope.holidayList = data;
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
var m = null;
if ($scope.selectable == "Yes") {
m = true;
} else {
m = false;
}
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 400,
editable: true,
selectable: m,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startDate = start.toDate();
obj.endDate = moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
// calendar.fullCalendar('unselect');
},
dayRender: function(date, cell) {
var today = new Date();
today = moment(today).toDate();
var end = new Date();
end = moment(end).toDate();
end.setDate(today.getDate() + 7);
date = moment(date).toDate();
angular.forEach($scope.holidayList, function(value) {
if (((moment(value.holiday_date).format("YYYY-MM-DD")) == moment(date).format("YYYY-MM-DD"))) {
cell.css("background-color", "#2bbbad");
//$('.date').text('Today');
cell.prepend("<span style=\"max-width:200px;word-wrap:break-word;margin-top:10px;\">" + value.description + "</span>");
cell.prepend("<br>")
}
});
},
eventRender: $scope.eventRender,
}
};
console.log($scope.holidayList);
}).error(function(data, status, headers, config) {
alert("error from holidaylist");
});
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get($scope.url, {
cache: true,
params: {}
}).then(function(data) {
console.log(data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
if (value.approvalStatus == "Approved") {
var k = '#114727';
} else {
k = '#b20000'
}
$scope.events.push({
title: value.signum,
description: value.signum,
start: value.startDate,
end: value.endDate,
allDay: value.isHalfDay,
stick: true,
status: value.approvalStatus,
backgroundColor: k
});
});
});
}
}
}]);
g-include
<div id="controllerid">
<div class="row" >
<div class="col s10 m10 l10">
<div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
</div>
</div>
<!-- Modal Structure -->
<div id="modal1" class="modal" ng-controller="MyAddController">
<div class="modal-content">
<h4>Apply Leave</h4>
<div class="row">
<form class="col s12" id="form1">
<div class="row modal-form-row">
<div class="input-field col s6">
<input id="num" type="text" class="validate" ng-model="test.num"> <label for="num">num</label>
</div>
<div class="input-field col s6">
<input id="ename" type="text" class="validate" ng-model="test.title"> <label for="ename">Employee Name</label>
</div>
</div>
<div class="row">
<form class="col s12">
<div class="row modal-form-row">
<div class="input-field col s5">
<input id="startDate" type="text" class="validate" value="{{selectionDate.startDate | date}}" readonly >
</div>
<div class="input-field col s5">
<input id="endDate" type="text" class="validate" value="{{selectionDate.endDate | date}}" readonly>
</div>
<div class="input-field col s1">
<p>
<input type="checkbox" id="test6" ng-model="test.isHalfDay" /> <label for="test6">Half Day</label>
</p>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="description" type="text" class="validate" ng-model="test.description"> <label for="description">Description</label>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit <i class="material-icons right">send</i>
</button>
</div>
</div>
and my add controller
app.controller("MyAddController", function($scope, $http,$rootScope,calendarSer) {
$scope.test = {};
$scope.add = function() {
$("#modal1").closeModal();
$scope.test1=$rootScope.selectionDate;
var jsonData = JSON.stringify($.extend({}, $scope.test, $scope.test1));
console.log(""+jsonData);
$http({
url: "rest/leave/create",
method: "POST",
data: jsonData,
headers: {'Content-Type': 'application/json'}
}).success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
}).error(function(data, status, headers, config) {
alert("error from create leave");
})
}
});
ANy help would be appreciated
In your "success" function after you run the "create" function, you can simply add the event to fullCalendar using the same data, via the built-in "renderEvent" function.
Something like this (I don't know Angular, so you may need to adjust this slightly to get your calendar element into context, but hopefully you understand the idea). I am also assuming that jsonData contains all the relevant event data which we can use for this:
.success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
//add the event to the calendar UI without refreshing the events
$('[ui-calendar]').fullCalendar("renderEvent",
{
start: jsonData.startDate,
end: jsonData.endDate,
title: jsonData.title
},
true //make it stick even when the view changes
);
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
You may need to add more fields, or you may need to get momentJS to parse the values in startDate / endDate, depending exactly what those fields output.
The "renderEvent" method can be found in the fullCalendar documentation here: https://fullcalendar.io/docs/event_rendering/renderEvent/

Angular contact form - undefined field after after sending

Here is my index.html
<div data-ng-controller="help">
<div id="messages" class="alert alert-success" data-ng-show="messages" data-ng-bind="messages"></div>
<div data-ng-show="progress.active()" style="color: red; font-size: 50px;">Sending…</div>
<form name="helpForm" novalidate role="form">
<div class="form-group">
<label for="name">Your Name </label>
<span class="label label-danger" data-ng-show="submitted && helpForm.name.$error.required">Required!</span>
<input type="text" name="name" data-ng-model="userName" class="form-control" required />
</div>
<div class="form-group">
<label for="email">Your E-mail address</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.email.$error.required">Required!</span>
<span class="label label-danger" data-ng-show="submitted && helpForm.$error.email">Invalid email!</span>
<input type="email" name="email" data-ng-model="userEmail" class="form-control" required />
</div>
<div class="form-group">
<label for="message">Message</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.message.$error.required">Required!</span>
<textarea name="message" data-ng-model="userMessage" class="form-control" required></textarea>
</div>
<button data-ng-disabled="progress.active()" data-ng-click="submit(helpForm)" class="btn btn-default">Submit</button>
</form>
And part of my app.js
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
$scope.subjectListOptions = {
'bug': 'Report a Bug',
'account': 'Account Problems',
'mobile': 'Mobile',
'user': 'Report a Malicious User',
'other': 'Other'
};
$scope.progress = promiseTracker();
$scope.submit = function(form) {
$scope.submitted = true;
if (form.$invalid) {
return;
}
var $promise = $http({
method: 'POST',
url:'api/contactUs',
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
})
.success(function(data, status, headers) {
if (data.status == 'OK') {
$scope.userName = null;
$scope.userEmail = null;
$scope.userMessage = null;
$scope.messages = 'Your form has been sent!';
$scope.submitted = false;
} else {
$scope.messages = 'Oops, we received your request, but there was an error processing it.';
$log.error(data);
}
})
.error(function(data, status, headers) {
$scope.progress = data;
$scope.messages = 'There was a network error. Try again later.';
$log.error(data);
})
.finally(function() {
$timeout(function() {
$scope.messages = null;
}, 9000);
});
After sending the letter to mail, all fields (name, email, message) in the form are displayed as "Undefined"
I use an node.js server and connect via api (api/contactUs)
I can not understand what the problem is, already tried everything I could, but the error remains.
Please help with the solution of this problem.
Thank you in advance!
When you use POST method, you should pass data object instead of params object.
Change this:
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
To this:
data: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}

POST data to server using AngularJS (ionic framework)

I'm trying to post data to a server from my ionic app. The URL to use is in a variable. Here is what I tried:
First I've created a service like this:
.service('PostTuto', ['$http',function($http) {
this.servicioPostTuto = function(tema,ubicacion,horario,nom_coe) {
return $http({
method: 'POST',
url: 'http://"""""".""".""""."""":8080/smartlandiotv2/webresources/entidades.datos/insert?apikey=3bff8615827f32442199fdb2ed4df4&trama={"Nombre":"'+tema+'","Apellido":"'+ubicacion+'","Sexo":"'+horario+'","Residencia":"'+nom_coe+'"}',
});
};
}])
in this part I send in my url the variables tema, ubicacion, horario, nom_coe and my controller. I've done this:
$scope.data = {};
$scope.create=function(){
$scope.nom_coe="IDfromSubject"
PostTuto.servicioPostTuto($scope.data.tema,$scope.data.ubicacion,$scope.data.horario,$scope.nom_coe)
.success(function(data){
var alertPopup = $ionicPopup.alert({
title: 'created'
});
})
.error(function(data){
var alertPopup = $ionicPopup.alert({
title: 'Error to post data'
});
});
};
//FIN POSTEAR DATOS A SERVIDOR
In this part I receive the data from input in my html file.
<label class="item item-input item-stacked-label">
<span class="input-label"><strong>Tema:</strong></span>
<input type="text" ng-model="data.tema" ng-disabled="editar">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label"><strong>Ubicacion:</strong></span>
<input type="text" ng-model="data.ubicacion" ng-disabled="editar">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label"><strong>Horario:</strong></span>
<input type="text" ng-model="data.horario" ng-disabled="editar">
</label>
<a class="button button-block icon-left ion-ios-compose button-positive"
ng-disabled="!data.tema || !data.ubicacion || !data.horario" ng-click="create()">
create
</a>
When I try to post data, my app returns me an error "Error to post data", how can I fix that?
Sending your API key in querystring is not a good way.You could try this
In Controller Js
$scope.data=new Object();
$scope.create=function(){
PostTuto.servicioPostTuto($scope.data)
.success(function(data){
var alertPopup = $ionicPopup.alert({
title: 'created'
});
})
.error(function(data){
var alertPopup = $ionicPopup.alert({
title: 'Error to post data'
});
});
};
And in your AppConfig.js
app.run(function($http){
$http.defaults.headers.common['APIKey'] = "3bff8615827f32442199fdb2ed4df4";
})
And in your service
.service('PostTuto', ['$http',function($http) {
this.servicioPostTuto = function(data) {
return $http.post('http://"""""".""".""""."""":8080/smartlandiotv2/webresources/entidades.datos/insert',data);
}
}])
Now from serverside ,you could get your APIKey from Request header for your purpose

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.

Angular Form Post

I have the following code and when I submit the request; I get request failed. The data is not going to the server. Any idea why?
All I need is a simple form submission with the code below. I think the issue is where I'm collecting the form data using the config section. I looked around and that's how I added that. Any help will be appreciated.
Thanks.
<!-- Main Content -->
<div class="container">
<div class="page-header" ng-controller="NotesCtrl">
<h1>{{title}}</h1>
<form class="row-height" name="Form1" ng-submit="processForm('ajaxSubmitResult')">
<!--ng-submit="processForm(formData, 'ajaxSubmitResult') -->
First Name:
<input type="text" ng-model="formData.firstname" class="spacer" required/>
Last Name:
<input type="text" ng-model="formData.lastname" class="spacer" required/>
<!--<button class="btn btn-primary" ng-click="insert(formData)">Add</button>-->
<button type="submit" class="btn btn-success">Add Name</button>
</form>
<hr/>
<h4>Raw Data</h4>
{{formData}}
<hr/>
<h4>Submit Results</h4>
<span id="submitDebugText">{{ajaxSubmitResult | json}}</span>
</div>
</div>
<script>
// define angular module/app
var formApp = angular.module('formApp', []);
function NotesCtrl($scope, $http) {
$scope.title = "Test App";
$scope.formData = {};
$scope.processForm = function (resultVarName) {
var config = {
params: {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}
};
$http.post("//", null, config)
.success(function (data, status, headers, config) {
$scope[resultVarName] = data;
})
.error(function (data, status, headers, config) {
$scope[resultVarName] = "bugger! Errors.";
});
};
}
</script>
When you do something like this in the view:
<input type="text" ng-model="formData.firstname" class="spacer" required/>
In the controller, you access the property with
$scope.formData.firstName
This issue seems to be that you aren't including the formData here:
var config = {
params: {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}
};
Change that to
var config = {
params: {
'firstname': $scope.formData.firstname,
'lastname': $scope.formData.lastname
}
};
And you should be good to go.

Resources