How to use multiple ng-model in one function? - javascript

Hi everyone I'm creating an database using indexed db in Angular js. My task is to save the data into database and my question is can we use multiple ng-model in one function ? Let me show you my code to make it clear.
index.html
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#3.1.1" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script data-require="angular.js#1.2.13" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script data-require="angular.js#1.2.13" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular-animate.js"></script>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body>
<div data-ng-app="indexDBSample" data-ng-controller="TodoController as vm">
<table>
<tr data-ng-repeat="todo in vm.todos">
<td>{{todo.text}}</td>
<td>[X]</td>
</tr>
</table>
<br />
<input type="text" data-ng-model="vm.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
<input type="button" value="Add" data-ng-click="vm.addTodo()" />
<input type="button" value="Refresh" data-ng-click="vm.refreshList()" />
</div>
</body>
</html>
script.js
var app = angular.module('indexDBSample', []);
app.factory('indexedDBDataSvc', function($window, $q){
var indexedDB = $window.indexedDB;
var db=null;
var lastIndex=0;
var open = function(){
var deferred = $q.defer();
var version = 1;
var request = indexedDB.open("todoData", version);
request.onupgradeneeded = function(e) {
db = e.target.result;
e.target.transaction.onerror = indexedDB.onerror;
if(db.objectStoreNames.contains("todo")) {
db.deleteObjectStore("todo");
}
var store = db.createObjectStore("todo",
{keyPath: "id"});
};
request.onsuccess = function(e) {
db = e.target.result;
deferred.resolve();
};
request.onerror = function(){
deferred.reject();
};
return deferred.promise;
};
var getTodos = function(){
var deferred = $q.defer();
if(db === null){
deferred.reject("IndexDB is not opened yet!");
}
else{
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
var todos = [];
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(result === null || result === undefined)
{
deferred.resolve(todos);
}
else{
todos.push(result.value);
if(result.value.id > lastIndex){
lastIndex=result.value.id;
}
result.continue();
}
};
cursorRequest.onerror = function(e){
console.log(e.value);
deferred.reject("Something went wrong!!!");
};
}
return deferred.promise;
};
var deleteTodo = function(id){
var deferred = $q.defer();
if(db === null){
deferred.reject("IndexDB is not opened yet!");
}
else{
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
var request = store.delete(id);
request.onsuccess = function(e) {
deferred.resolve();
};
request.onerror = function(e) {
console.log(e.value);
deferred.reject("Todo item couldn't be deleted");
};
}
return deferred.promise;
};
var addTodo = function(todoText){
var deferred = $q.defer();
if(db === null){
deferred.reject("IndexDB is not opened yet!");
}
else{
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
lastIndex++;
var request = store.put({
"id": lastIndex,
"text": todoText
});
request.onsuccess = function(e) {
deferred.resolve();
};
request.onerror = function(e) {
console.log(e.value);
deferred.reject("Todo item couldn't be added!");
};
}
return deferred.promise;
};
return {
open: open,
getTodos: getTodos,
addTodo: addTodo,
deleteTodo: deleteTodo
};
});
app.controller('TodoController', function($window, indexedDBDataSvc){
var vm = this;
vm.todos=[];
vm.refreshList = function(){
indexedDBDataSvc.getTodos().then(function(data){
vm.todos=data;
}, function(err){
$window.alert(err);
});
};
vm.addTodo = function(){
indexedDBDataSvc.addTodo(vm.todoText).then(function(){
vm.refreshList();
vm.todo="";
}
, function(err){
$window.alert(err);
});
};
vm.deleteTodo = function(id){
indexedDBDataSvc.deleteTodo(id).then(function(){
vm.refreshList();
}, function(err){
$window.alert(err);
});
};
function init(){
indexedDBDataSvc.open().then(function(){
vm.refreshList();
});
}
init();
});
I have used three ng-model with three different input field but what i need is to use all the three ng-model in one function i.e in
vm.addTodo = function(){
indexedDBDataSvc.addTodo(vm.todoText).then(function(){
vm.refreshList();
vm.todo="";
}
, function(err){
$window.alert(err);
});
};
to get three different output.Please help me with this because i'm new to angular.js
And here is my plunker :http://plnkr.co/edit/3yM2j9Dgv5FzEP2L9pYH?p=preview

Bind the input in the form as:
<form name="my_form">
<input type="text" data-ng-model="vm.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
<button type="button" value="Add" data-ng-Click="vm.addTodo(vm)">Add</button>
<button type="button" value="Refresh" data-ng-Click="vm.refreshList()">Refresh</button>
</form>
In the app.js, in your function, you get all your data from data-ng-model.
vm.addTodo = function(vm){
alert(angular.toJson(vm));
console.log(angular.toJson(vm.todoText));//check the value in console
console.log(angular.toJson(vm.todoText1));
console.log(angular.toJson(vm.todoText2));//you can use the value as vm.todoText,vm.todoText1 and so on.
indexedDBDataSvc.addTodo(vm.todoText).then(function(){
vm.refreshList();
vm.todo="";
}
, function(err){
$window.alert(err);
});
};
The rest of the logic depends upon whatever you do with the data.
Updates: As per your need of comment.Check your addition of data using your refresh button.Passing the vm as in the original code, created conflict in the controller section so i changed the ng-model to form so that i could get the exact model value.
<form name="my_form">
<input type="text" data-ng-model="form.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
<input type="text" data-ng-model="form.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
<input type="text" data-ng-model="form.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
<button type="button" value="Add" data-ng-Click="vm.addTodo(form)">Add</button>
<button type="button" value="Refresh" data-ng-Click="vm.refreshList()">Refresh</button>
</form>
app.js
vm.addTodo = function(vm){
angular.forEach(vm,function(key,value){
indexedDBDataSvc.addTodo(key).then(function(){
$window.location.reload();
vm.todo="";
}
, function(err){
$window.alert(err);
});
});
};
Checkout this plunkr: http://plnkr.co/edit/xyR2W1GpylMXofIKi1BR?p=preview

Related

Fill textbox from url query and call function

<input type="text" id="tnum" maxlength="50" placeholder="Enter Your Tracking ID" />
<input class="btn" type="button" value="TRACK" onclick="doTrack()" />
<div id="YQContainer"></div>
So basically, I have a page that can track packages for my customers. I want to be able to send them a link in their email that will automatically track their package from the link. ( they don't have to type in their tracking id and click track when they go to my tracking page )
example.com/track?tnum=3298439857
This is what i'm using to track packages.
https://www.17track.net/en/externalcall/single
The basic idea is as follows:
Wait for page to load
Parse the URL and extract needed query parameter
Set the value of the form element
Call the doTrack() function
// Handy function to parse the URL and get a map of the query parameters
function parseQueryParameters(url) {
var qp = {};
if (!url) {
return qp;
}
var queryString = url.split('?')[1];
if (!queryString) {
return qp;
}
return queryString.split('&')
.reduce(function(m, d) {
var splits = d.split('=');
var key = splits[0];
var value = splits[1];
if (key && value) {
m[key] = value;
}
return m;
}, qp);
}
//Wait for page to load
window.onload = function() {
//Extract tnum query parameter
var qp = parseQueryParameters(window.location.href);
//If no parameter is provided, do nothing
if (!qp.tnum) return;
//Set the value of the form element
document.getElementById("tnum").value = qp.tnum;
// Call doTrack
doTrack();
}
//Temporary doTrack function - remove when integrating ;)
function doTrack() {
console.log(document.getElementById("tnum").value)
}
<input type="text" id="tnum" maxlength="50" placeholder="Enter Your Tracking ID" />
<input class="btn" type="button" value="TRACK" onclick="doTrack()" />
<div id="YQContainer"></div>
<html>
<head>
<script>
function setURL(){
var dt_value = document.getElementById("tnum").value;
//just test here ..what is coming..
alert(dt_value );
var sjdurl = "example.com/track?tnum="+dt_value;
popup = window.open(sjdurl,"popup"," menubar =0,toolbar =0,location=0, height=900, width=1000");
popup.window.moveTo(950,150);
}
</script>
</head>
<body>
<input type="Text" id="tnum" maxlength="25" size="25"/>
<input type='button' onclick='setURL()' value='SUBMIT'>
</body>
</html>
function doTrack(tnum) {
var trackNumber = tnum;
window.open("example.com/track?tnum="+trackNumber);
}
$(".btn").on('click',function(e) {
e.preventDefault();
var tnum = $('#tnum').val();
if (tnum!="") {
doTrack(tnum);
} else {
return false;
}
});

How to return object in google app script

I want to return the object from code.gs to html file on google app script. But I couldnt return the values. I want to display the values on the html interface. I couldnt return value at "alert(retsearch[0].yourname);"
Please help, Thank you!!
Code.gs
function getData() {
var ss=SpreadsheetApp.openById('1PWJyASHmjJ_W8-72u8bbrGbN-Nv6kdkCvjdmYuNNlEY');
var sheet=ss.getSheetByName('invoice1');
return sheet;
}
function processSearch(searchform){
var sheet = getData();
var data = ObjApp.rangeToObjects(sheet.getDataRange().getValues());
var searchfname=searchform.surname;
var searchcname=searchform.scustomername;
var searchpayementdate=searchform.spayementdate;
var results = [];
for(var i=0 ; i < data.length ; i++) {
if(searchfname == data[i].yourname || searchcname == data[i].customername || searchpayementdate == data[i].paymentday ) {
var events ={yourname:data[i].yourname, customername:data[i].customername,paymentday:data[i].paymentday };
results.push(events);
}
}
Logger.log(results);
return results;
}
Html file
<form id="fsrecord">
<input type="text" name="surname" id="surname" placeholder="by your name"/> <br/>
<input type="text" name="scustomername" id="scustomername" placeholder="by customer name"/> <br/>
<input type="date" name="spayementdate" id="spayementdate" placeholder="by payment date"> <br>
<input type="submit" value="search" />
</form>
<script>
$( document ).ready(function() {
$("#fsrecord").submit(function() {
google.script.run.withSuccessHandler(function(retsearch){
alert(retsearch[0].yourname);
}).processSearch(this);
});
});
</script>
You can convert the stringify the data at the server side and parse the JSON at the client side.
code.js
function processSearch(searchform){
...
...
return JSON.stringify(results);
}
index.html
$(document).ready(function () {
$("#fsrecord").submit(function () {
google.script.run.withSuccessHandler(function (retsearch) {
var response = JSON.parse(retsearch);
alert(response[0].yourname);
}).processSearch(this);
});
});

Show only clicked element values from multiple ng-click events angularjs

i have 10 more ng-click events, but i want to show only clicked element value where i have to change, but i updated in code there was so many true or false duplicates i have to write, pls help me that have to show only clicked ng-show values without using 'true or false' booleen functions in each click event.
var app = angular.module('myapp', ['ngSanitize']);
app.controller('AddCtrl', function ($scope, $compile) {
$scope.field = {single: 'untitled',single2:'default',single3:'enter'};
$scope.addName1 = function (index) {
var name1html = '<fieldset id="name1" ng-click="selectName1($index)"><label ng-bind-html="field.single"></label><input type="text" placeholder="Enter name"><button ng-click="removeName1($index)">-</button></fieldset>';
var name1 = $compile(name1html)($scope);
angular.element(document.getElementById('drop')).append(name1);
};
$scope.removeName1 = function (index) {
var myEl = angular.element(document.querySelector('#name1'));
myEl.remove();
};
$scope.selectName1 = function (index) {
$scope.showName1 = true;
$scope.showName2 = false;
$scope.showName3 = false;
};
$scope.addName2 = function (index) {
var name2html = '<fieldset id="name2" ng-click="selectName2($index)"><label ng-bind-html="field.single2"></label><input type="text" placeholder="Enter name"><button ng-click="removeName2($index)">-</button></fieldset>';
var name2 = $compile(name2html)($scope);
angular.element(document.getElementById('drop')).append(name2);
};
$scope.removeName2 = function (index) {
var myEl = angular.element(document.querySelector('#name2'));
myEl.remove();
};
$scope.selectName2 = function (index) {
$scope.showName2 = true;
$scope.showName1 = false;
$scope.showName3 = false;
};
$scope.addName3 = function (index) {
var name3html = '<fieldset id="name3" ng-click="selectName3($index)"><label ng-bind-html="field.single3"></label><input type="text" placeholder="Enter name"><button ng-click="removeName3($index)">-</button></fieldset>';
var name3 = $compile(name3html)($scope);
angular.element(document.getElementById('drop')).append(name3);
};
$scope.removeName3 = function (index) {
var myEl = angular.element(document.querySelector('#name3'));
myEl.remove();
};
$scope.selectName3 = function (index) {
$scope.showName3 = true;
$scope.showName1 = false;
$scope.showName2 = false;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="AddCtrl">
<div id="drop"></div>
<button ng-click="addName1($index)">Name1</button>
<button ng-click="addName2($index)">Name2</button>
<button ng-click="addName3($index)">Name3</button>
<form ng-show="showName1">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single">
</div>
</form>
<form ng-show="showName2">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single2">
</div>
</form>
<form ng-show="showName3">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single3">
</div>
</form>
</body>
</html>
here is plunkr http://plnkr.co/edit/oFytWlQMIaCaeakHNk71?p=preview
You will need "ng-repeat" in the HTML. Set an Array on $scope and let the template determine what HTML elements to add. Typically, $index is only set by ng-repeat.
Read more here: https://docs.angularjs.org/api/ng/directive/ngRepeat

function will not return a value

I'm trying to write a file upload function that will return either a true or false after it uploads the file. The only return I can currently get is undefined. I have tried a few variations of the code, but I can't figure it out. I believe it's a latency or scope issue, but not really sure. Take a look and tell me what you guys think.
HTML
<div id="add-form">
make : <input type="text" id="make" name="make" />
type : <input type="text" id="type" name="type" />
caliber : <input type="text" id="caliber" name="caliber" />
cost : <input type="text" id="cost" name="cost" />
description : <textarea id="description"></textarea>
<form id="image-form">
image : <input type="file" id="image" name="image" />
</form>
<button id="add-item">ADD ITEM</button>
</div>
JQUERY
$(function()
{
$('#add-item').click(function()
{
console.log(uploader());
});
var uploader = function uploader()
{
var iframe = $('<iframe name="postiframe" id="postiframe" style="display:none" />');
$("body").append(iframe);
var form = $('#image-form');
form.attr("action","hub.php?handler=image");
form.attr("method","post");
form.attr("enctype","multipart/form-data");
form.attr("encoding","multipart/form-data");
form.attr("target","postiframe");
form.attr("file",$('#image').val());
form.submit();
$("#postiframe").load(function()
{
var _frame = $("#postiframe").contents().find('body').html();
var obj = $.parseJSON(_frame);
if(obj['status']==true)
{
return true;
}
else
{
return false;
}
});
}
});
The problem is that you're returning a value from your ajax callback
$("#postiframe").load(function() {
// ...
return true;
By the time this line of code has been reached, the original function has already terminated, returning nothing, which of course evaluates as undefined
var uploader = function uploader()
{
var iframe = $('<iframe name="postiframe" id="postiframe" style="display:none" />');
$("#postiframe").load(function()
{
var _frame = $("#postiframe").contents().find('body').html();
var obj = $.parseJSON(_frame);
if(obj['status']==true)
{
//function has already ended by this point!
return true;
}
else
{
//function has already ended by this point!
return false;
}
});
//you need to return something HERE
}
I'd say your best bet would be to pass in two callback functions, one to be run if the uploads succeeds, and the other if it fails. This won't get you to the point where the function will return true or false based on the result of the upload, but it will allow you to specify code to be run based on whether or not the upload is successful
var uploader = function uploader(successCallback, failureCallback)
{
var iframe = $('<iframe name="postiframe" id="postiframe" style="display:none" />');
$("#postiframe").load(function()
{
var _frame = $("#postiframe").contents().find('body').html();
var obj = $.parseJSON(_frame);
if(obj['status']==true)
{
if (typeof successCallback === 'function')
successCallback();
}
else
{
if (typeof failureCallback === 'function')
failureCallback();
}
});
}
The solution is you should implement a callback pattern to deal with the async nature. Here is is oversimplified.
var uploader = function(callback) {
$("postiframe").load(function () {
// success
callback(true);
});
};
Usage
uploader(function (success) {
});

Conversion from jQuery into JavaScript

I've a script:
<form id="myform">
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="submit" value="submit">
</form>
<img id="image" src="http://mydomain.com/empty.gif" />
<script>
$(document).ready(function () {
$("#myform").submit(function (ev) {
ev.preventDefault();
var val1 = $("#input1").val();
var val1 = $("#input2").val();
$("#image").attr("src", "http://mydomain.com/image?val1="+val1+"&val2="+val2);
});
});
</script>
How would it look like if written in JavaScript?
<img id="image" src="http://mydomain.com/empty.gif" />
<script>
window.onload = function() { // Not all browsers support DOMContentLoaded
document.getElementById("myform").onsubmit = function() {
var val1 = document.getElementById("input1").value;
var val2 = document.getElementById("input2").value;
document.getElementById("image").src="http://mydomain.com/image?val1="+val1+"&val2="+val2;
return false;
};
};
</script>
If you NAME the fields you can use
window.onload = function() {
document.getElementById("myform").onsubmit = function() {
document.getElementById("image").src="http://mydomain.com/image?val1="+this.input1.value+"&val2="+this.input2.value;
return false;
};
};
You MAY want to escape the two values

Categories

Resources