How to push dynamic data to JavaScript object? - ionic-framework

I am new to the Ionic Framework. I just started building a few functionalities in AngularJS. Here, what I want is to enter the email and booking ID of a user in an HTML page and then redirect it to other pages which displays all email ids and booking id... Here is my code:
Reservation.html:
<form ng-submit = "goBooking(data)">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="Enter Your Email Id" ng-model="data.emailId" required>
</label>
<label class="item item-input">
<input type="text" placeholder="Enter Your Booking Id" ng-model="data.bookingID" required>
</label>
</div>
<div class="padding">
<input type="submit" class="button button-block button-positive" value = "Submit" />
</div>
</form>
</ion-content>
</ion-view>
Reservation.JS
Controller.js:
.controller('reservationCtrl', function($scope, $state, $stateParams) {
$scope.toDoListItems = [{
emailId: 'versha',
bookingID: '123'
}, {
emailId: 'rahul',
bookingID: '456'
}];
$scope.getTotal = function(){
return $scope.toDoListItems.length;
}
$scope.goBooking = function(data){
$scope.toDoListItems.push({emailId:data.emailId,bookingID:data.bookingID});
$state.go('myBookingDetails');
data.emailId = ' ';
data.bookingID = ' ';
};
});
myBookingDeatils.html:
<ion-view view-title="Hotel Reception">
<ion-content>
<ion-list>
<ion-item ng-controller = "reservationCtrl" ng-repeat="item in toDoListItems">
<p> Welcome {{item.emailId}} !!!! </p>
ion-item>
</ion-list>
</ion-content>
</ion-pane>
</ion-view>
After running this,
I am getting output as
Welcome, Versha!!
Welcome, Rahul!!
I am not getting that email ID and Booking ID. What I am entering on my Reservation.html. I think my input values are not being set in the toDoListItems.
Somewhere, this code is not inserting the values $scope.toDoListItems.push({emailId:data.emailId,bookingID:data.bookingID});
Please Suggest!! Thanks in Advance!!

I am assuming you are using the same controller for each state? When you change states you reload your controller, which resets your $scope.toDoListItems array to it's inital state. You are going to want to save your toDoListItems in a Service. So...
Controller:
.controller('reservationCtrl', function($scope, $state, $stateParams, toDo) {
$scope.getTotal = function(){
return toDo.toDoListItems.length;
}
$scope.goBooking = function(data){
toDo.toDoListItems.push({
emailId:data.emailId,
bookingID:data.bookingID
});
$state.go('myBookingDetails');
data.emailId = null;
data.bookingID = null;
};
});
Service:
.factory('toDo', [function () {
var toDoListItems = [{
emailId: 'versha',
bookingID: '123'
}, {
emailId: 'rahul',
bookingID: '456'
}];
return {
toDoListItems : toDoListItems
};
}]);
This will ensure that the data survives the state change, however if you want this data to persist permanently and stay on page reloads etc.. you will need to hook up a database, if you are purely a front end guy I suggest looking at Firebase

A very simple way to accomplish this would be to just use $localstorage.
Something like this:
$scope.goBooking = function(data){
$scope.toDoListItems.push({emailId:data.emailId,bookingID:data.bookingID});
$localstorage.setObject('toDoListItems', $scope.toDoListItems);
$state.go('myBookingDetails');
};
And then inside of your new view (where the controller and scope are getting refreshed as Jacob pointed out)
$scope.toDoListItems = $localstorage.getObject('toDoListItems');
You'll just need to add the $localstorage service to you services (detailed in link below). For more info on using localstorage with Ionic, visit: http://learn.ionicframework.com/formulas/localstorage/

Related

Populate email "to" field with address from reactive-table in Meteor

I have a reactive-table in Meteor that lists usernames and email addresses from the users collection. I want to click on the email address and have a modal pop up with that email address filled in the "to" field.
Template with reactive table and email modal:
<template name="Compete">
{{> reactiveTable class="table table-bordered table-hover" settings=settings }}
{{> emailModalTemplate settings.fields}}
</template>
settings helper:
Template.Compete.helpers({
settings: function(){
if (Meteor.user()){
var col = Meteor.users.find({ }, {fields: {profile:1, emails:1} } );
var email = 'emails.0.address';
return {
collection: col,
showFilter: false,
showNavigation: 'never',
fields: [{
key: 'profile.userName',
label: 'Player'
}, {
key: email,
label: 'Email',
fn: function(email){
return new Spacebars.SafeString(
''+email+''
);
}
}]
};
}
},
And here is the email modal template:
<template name="emailModalTemplate">
<div class="modal fade" id="emailModal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Send Email</h4>
</div>
<div class="modal-body">
<form role="form" id="email-form">
<input type="email" id="inputEmail" placeholder="{{addToAddr}}">
<input type="text" id="inputSubject" placeholder="Subject">
<textarea id="inputBody" rows="5" placeholder="Message"></textarea>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Send</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
At this point, the {{addToAddr}} helper is just console logging "this" but all I can get back are the actual keys from the reactive table settings, but not the values. Am I passing in the right thing by passing in the reactive table helper?
What else could I pass in to the email modal template to get the actual email values that I can then use to populate the email to address field?
EDIT: One last note to add:
My click event is as follows:
'click .sndLnk': function(e){
e.preventDefault();
console.log( $(e.currentTarget).attr('value') );
$('#emailModal').modal('show');
}
The console.log here accurately shows the email address I want to pass in, but how do I pass that in to the email modal form? I assumed via the helper, but maybe that's wrong?
I tinkered with it some more and resolved it by setting a session variable in a new "external" helper function, "external" in that it is just a var I set, not within Template.myTemplate.helpers:
var openEmailModal = function(email) {
Session.set('theEmailAddr', email);
$('#emailModal').modal('show');
}
Then I modified the click event to call the new var/function:
'click .sndLnk': function(e){
e.preventDefault();
var email = $(e.currentTarget).attr('value');
openEmailModal(email);
}
At the end of the day this seems pretty basic, I made it into much more than it was I guess... Thanks to all who viewed.

Ionic Return value navigation on different view

I have a form view with an input text. When I click on this input, another view is opened.
In this view, there are an input search and a list. The list change when I change a text from the input search.
I want when I click one item of the list, this view gets closed and the input text change. But I don't know how I can do that.
Can you help me please?
the input text in my form view:
<div class="select-typeevent">
<ion-item nav-clear menu-close ui-sref="menu.setlocation">
<label class="padding">
Address:
</label>
</ion-item>
</div>
My searchview:
<ion-view view-title="Address" class="content">
<ion-content>
<h1>Address</h1>
<div class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios-search placeholder-icon"></i>
<input class="border-none" name="txtssearch" type="search" placeholder="Search" ng-model="addresssearch" ng-change="getGeocode(addresssearch)">
</label>
<button class="button button-clear" ng-click="addresssearch='';getGeocode(addresssearch)">
Annuler
</button>
</div>
<div class="list" >
<a ng-repeat="addr in addresslist" class="item" ng-click="setaddress(addr)">
{{addr.address}} {{addr.location}}
</a>
</div>
</ion-content>
</ion-view>
And the js:
'Use Strict';
angular.module('App').controller('setlocationController', function ($scope,$state, $cordovaOauth, $localStorage, $location, $http, $ionicPopup,$firebaseObject,$ionicHistory, Auth, FURL, Utils) {
$scope.getGeocode = function (addresssearch) {
$scope.geodata = {};
$scope.queryResults = {};
$scope.queryError = {};
$http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + addresssearch)
.then(function (_results) {
$scope.addresslist = [];
$scope.queryResults = _results.data.results;
console.log($scope.queryResults);
$scope.queryResults.forEach(function(result) {
$scope.addresslist.push({ 'address': result.formatted_address, 'location': result.geometry.location });
});
},
function error(_error){
$scope.queryError = _error;
})
};
// Here I want when I click one item of the list, this view gets closed and the input text of formview change.
$scope.setaddress = function (addr) {
$scope.setaddress = addr;
$ionicHistory.backView();
}
Why not using an $ionicModal:
$scope.getGeocode = function (addresssearch) {
...
$scope.modal.show();
}
Previously set the modal:
$ionicModal.fromTemplateUrl('my-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
Where my-modal.html points to the template which shows geocode information.

Meteor - Data saving issue

I have this template:
<Template name="nuevoEjercicio">
<div class="container-fluid">
<div class="form-group">
<input type="text" class="form-control input-lg" name="ejercicio" placeholder="Ejercicio?"/>
<input type="number" class="form-control" name="repeticiones" placeholder="Repeticiones?" />
<input type="number" class="form-control" name="peso" placeholder="Peso?" />
<button type="submit" class="btn btn-success" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</Template>
that I use to capture and save to the database.
Then on my .js file I am trying to get the data and save it:
Template.nuevoEjercicio.events({
'click .btn btn-success': function (event) {
var ejercicio = event.target.ejercicio.value;
var repeticiones = event.target.repeticiones.value;
var peso = event.target.peso.value;
ListaRutina.insert({
rutina:"1",
ejercicio:ejercicio,
repeticiones:repeticiones,
peso:peso,
});
// Clear form
event.target.ejercicio.value = "";
event.target.repeticiones.value = "";
event.target.peso.value = "";
// Prevent default form submit
return false;
}
});
}
as I understand, when I click on any object that has the btn btn-success style....but is not the case. For some obscure reason -for me- is not working.
Can you check it and give me some advice?
Thanks!
First of all, there's an error in you selector. It's 'click .btn.btn-success', not 'click .btn btn-success'.
Also you can't do that event.target.ejercicio.value thing. event.target is the element that was clicked. You'll have to do something like this:
'click .btn.btn-success': function (event, template) {
var ejercicio = template.$('[name=ejercicio]').val()
...
OK
What after wasting hours and hours the solution is:
1- on the html file give your input an id:
<input type="number" class="form-control" **id="peso"** placeholder="Peso?" />
<button type="submit" class="btn .btn-success" id="**guardar**" />
so now you want to save data on the input when the button is clicked:
2- You link the button with the funcion via the id
Template.TEMPLATENAMEONHTMLFILE.events({
'click **#guardar**': function (event, template) {
var ejercicio = template.$("**#peso**").val();
and get the value linking using the input id.

How to edit data when combining angularjs and mongodb

I'm a beginner in the AngularJs and MongoDb world (i started learning today!!)
Actually i'm trying to do something very basic : Display a list of record, with an add button and a edit link with each record.
I'm using this lib https://github.com/pkozlowski-opensource/angularjs-mongolab to connect to mongoweb.
Actually my data is displayed, when i try to add a record it works, but the problem is when i try to display the edit form!
Here is my index.html file, in which i display the data with a form to add a record and with the edit links :
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
<form ng-submit="addTeam()">
<input type="text" ng-model="team.name" size="30" placeholder="add new team here">
<input type="text" ng-model="team.description" size="30" placeholder="add new team here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
And here is my edit.html code, which displays an edit form :
<div ng-controller="EditCtrl">
<form ng-submit="editTeam()">
<input type="text" name="name" ng-model="team.name" size="30" placeholder="edit team here">
<input type="text" name="description" ng-model="team.description" size="30" placeholder="edit team here">
<input class="btn-primary" type="submit" value="validate edit">
</form>
</div>
And finally my js code:
var app = angular.module('app', ['mongolabResource']);
app.constant('API_KEY', '____________________________');
app.constant('DB_NAME', 'groups');
app.factory('Teams', function ($mongolabResource) {
return $mongolabResource('teams');
});
app.controller('AppCtrl', function ($scope, Teams) {
$scope.teams = Teams.query();
$scope.addTeam = function() {
varteam = {
name: $scope.team.name,
description: $scope.team.description
};
$scope.teams.push(varteam);
Teams.save($scope.team);
$scope.team.name = '';
$scope.team.description = '';
};
});
app.controller('EditCtrl', function ($scope, Teams) {
//????????
});
My AppCtrl works perfecty, it displays the data w add records perfectly.
Now i want to add the js code for the edit, but i don't even know form where to start ? how do i a get the id parameter in the url ? how do i tell the view to fill out the form fields from the values from the database ? And finally how do i update the databse.
I know that i asked a lot of question but i'm really lost! thank you
There are of course many possible solutions.
One solution is to use angularjs routing. See http://docs.angularjs.org/tutorial/step_07 for a tutorial.
Basically replace your ul list with something like:
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
Then you can create a route that responde to your url:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/teams', {
templateUrl: 'partials/team-list.html',
controller: 'TeamListCtrl'
}).
when('/teams/:teamId', {
templateUrl: 'partials/team-detail.html',
controller: 'TeamDetailCtrl'
}).
otherwise({
redirectTo: '/teams'
});
}]);
In this way from the detail controller (that will replace your EditCtrl) you can access the id parameter using: $routeParams.teamId
Anyway I suggest to study well all the tutorials for a better overview.

view not refreshing after zend redirect

so what i am trying to do, is after the user submit some information, i make a call to a action call saveronda, to save the information on the database, after saving i want to redirect to another page, according to the firebug the html is correct, but the view isnt refreshing.
so here is the code
so in my /rondas/chooseronda ive got this
<span class="st-labeltext">Tags da ronda:</span>
<table id="toolbar2"></table>
<div id="ptoolbar2"></div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Nome da ronda:</span>
<input type="text" name="nomeronda" id="nomeronda">
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Inicial:</span>
<select id="tagini" name="tagini">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Final:</span>
<select id="tagfim" name="tagfim">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Ordem:</span>
<select id="ordem" name="ordem">
<option value="Sim">Sim</option>
<option value="Não">Não</option>
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="button-box" style="z-index: 460;">
<input id="button" class="st-button" type="submit" value="Submit" name="button">
<input id="button2" class="st-clear" type="reset" value="Cancel" name="button">
</div>
when the user press the button submit i am making an ajax call to /rondas/saveronda and send some data, here is the code:
<script language = "Javascript">
$(document).ready(function() {
$("#button").click(function () {
/*
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: param1, param2:param2 },
datatype: "json"
*/
//buscar o nome
/*var nomeronda=$("#nomeronda").val();
//buscar a ordem
var ordem=$("#ordem").val();
//tag inicial e tag final
var taginicial=$("#tagini").val();
var tagfinal=$("#tagfim").val();
if(taginicial==tagfinal)
{
alert("a tag inicial não pode ser a mesma que a tag final");
}
else
{
var tags="";
//var allRowsOnCurrentPage = $('#toolbar2').getDataIDs();
var ids = $("#toolbar2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = $('#toolbar2').jqGrid ('getRowData', rowId);
tags=tags+rowData.id_tag.toString()+' ';
}*/
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: "sasa"},
datatype: "json"
});
//}
});
});
</script>
in this case i am sending param1 with the value "sasa", and through firebug i am detecting the post to the /rondas/saveronda.
after saving the data i want to redirect the user to /rondas/list, so i have been trying different solution
public function saverondaAction()
{
// action body
/*
if($this->_request->isXmlHttpRequest())
{
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
$param3 = $this->_request->getParam('param3');
$param4 = $this->_request->getParam('param4');
$param5 = $this->_request->getParam('param5');
$rondasModel= new Application_Model_Ronda();
$this->_forward('list', 'rondas');
}
*
*/
$this->_helper->redirector->gotoRoute(
array(
'controller' => 'rondas',
'action' => 'list'
)
);
}
or using redirect or forward..
none have worked, the view is still the /rondas/choosetags and not /rondas/list
what is my error...
thanks in advance..
Your initial view is /rondas/chooseronda when user press submit you make ajax call to /rondas/saveronda and send some data to it. Now if this is successful you want to redirect from the initial page (/rondas/chooseronda) to /rondas/list.
If the redirect code written in action /rondas/saveronda is not working, then you could return a success message back to initial view (/rondas/chooseronda), there you'll need to detect the success message in jQuery ajax code. If successful, put the redirect jQuery code, that will redirect it to /rondas/list.