Adding objects to array in service - javascript

i've tried to add an object to my array savedTemplates in a service with the function getTemplates.
I've used a service for this in order to access the templates in multiple views.
Unfortunately, if i try to call my function, nothing happens.
services.js:
.factory('templateData', function(){
var savedTemplates = [
{"name":"Adam Müller", "iban":"AT29100020003000","image":"adam.jpg"},
{"name":"Ben Streicher","iban":"AT34900080007000","image":"ben.png"},
{"name":"Max Krossmann","iban":"AT23400050006000","image":"max.png"}
];
var getTemplates = function(){
return savedTemplates;
};
var addTemplates = function(insertName,insertIban){
savedTemplates.push=({"name": insertName, "iban": insertIban, "image": 'mike.png'});
alert("This is savedTemplates:" + savedTemplates);
};
return {
getTemplates:getTemplates,
addTemplates:addTemplates
};
})
template-save.html:
<button class="button button-large button-positive" ng-click="addTemplates(newreceiver,newiban)" ui-sref="tab.templates">
Speichern
</button>
I would be very grateful for any help, since I'm quite desperated already.

Here is a sample snippet.
You also have a problem in your factory addTemplates code, you should use savedTemplates.push ({ ... }], not savedTemplates.push = ({ ... }]
Snippet
angular.module('app', []);
angular.
module('app')
.controller('ExampleController', ['$scope', 'templateData', function($scope, templateData) {
$scope.addTemplates = templateData.addTemplates;
}])
.factory('templateData', function() {
var savedTemplates = [{
"name": "Adam Müller",
"iban": "AT29100020003000",
"image": "adam.jpg"
},
{
"name": "Ben Streicher",
"iban": "AT34900080007000",
"image": "ben.png"
},
{
"name": "Max Krossmann",
"iban": "AT23400050006000",
"image": "max.png"
}
];
var getTemplates = function() {
return savedTemplates;
};
var addTemplates = function(insertName, insertIban) {
savedTemplates.push ({
"name": insertName,
"iban": insertIban,
"image": 'mike.png'
});
console.log("This is savedTemplates:" + JSON.stringify(savedTemplates, null, 2));
};
return {
getTemplates: getTemplates,
addTemplates: addTemplates
};
});
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="addTemplates('Marty McFly', 'BTTF900080007000')">
Speichern
</button>
</body>
</html>

Related

MEAN Stack Get Username from UserId forEach row

I'm trying to get the user data (such as username) for each user on a row of reviews. I kept my user information (login credentials on another model/controller), so is there a way to access and show the username on the view?
Below is my JSON code:
{
"_id": "56873fc9182b3741059357d0",
"longitude": 113.83507800000007,
"latitude": 22.1533884,
"location": "Hong Kong",
"name": "Hong Kong",
"__v": 0,
"category": "Attraction",
"reviews": [
{
"comment": "Add the comment to the form",
"rating": 3.5,
"userId": 11,
"review_id": "44NL7kkwhy72"
},
{
"comment": "Hello test",
"rating": "3.4",
"userId": "56809c0cf0a264b101a1dd61",
"review_id": "jN7f1iFlQVha"
},
{
"comment": "Hello test ty",
"rating": "3.7",
"userId": "56863c8f2959b4c601fbd9eb",
"review_id": "QcJpw4yopF1q"
}
]
},
//view all reviews for a location
.controller('AllReviews', function($scope, $stateParams, LocFac, UserFac) {
id = $stateParams.id;
LocFac.getLocation(id).then(function(data) {
$scope.locations = data.data;
$scope.reviews = data.data.reviews;
//variables to show information on location reviews
$scope.lengthrev = (data.data.reviews).length;
$scope.locationname = data.data.name;
//addition of values and retrieve the value
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.lengthrev; i++){
var review = $scope.reviews[i];
User.getUser(review).then(function(datat) {
$scope.locun = datat.username;
});
total += review.rating;
}
return total;
}
grandtotal = $scope.getTotal();
//get average of all values \
$scope.averagereviews = grandtotal/($scope.lengthrev);
});
})
My location reviews view
<ion-view view-title="All Reviews" class="all_reviews">
<ion-content class="all_reviews">
<h3>{{ locationname }}</h3>
<h3>Average Rating: {{ averagereviews }} <ng-rate-it name="rating" ng-model="averagereviews" resetable="false" read-only="true"></ng-rate-it>/ {{ lengthrev }} Reviews </h3>
<ion-list>
<ion-item data-ng-repeat="location in locations.reviews">
<ng-rate-it name="rating" ng-model="location.rating" resetable="false" read-only="true"></ng-rate-it>
{{ location.userId }}
<h4>{{ location.review_id }}</h4>
<h4>{{ location.comment }}</h4>
</ion-item>
</ion-list>
Considering your two aysnc operations,(one to fetch reviews and another one to fetch usernames) I think this approach will be more suitable.
First fetch the reviews.
Display the reviews.
While displaying the reviews use the UserFac to fetch the username asynchronously using ng-init directive.
I have created a demo plunker as an example with the sample data you provided in question.
Example:
Demo Plunker
app.js
var app = angular.module("app", []);
app.factory('LocFac', function($http) {
var factory = {};
factory.getLocation = function(id) {
return $http({
method: 'GET',
url: 'data.json'
});
}
return factory;
});
app.factory('UserFac', function($http) {
var factory = {};
factory.getUser = function(id) {
return $http({
method: 'GET',
url: 'user.json'
});
}
return factory;
});
app.controller('AllReviews', function($scope, LocFac, UserFac) {
$scope.show = false;
$scope.testClick = function() {
id = "56873fc9182b3741059357d0";
LocFac.getLocation(id).then(function(data) {
$scope.reviews = data.data.reviews;
$scope.lengthrev = (data.data.reviews).length;
$scope.show = true;
});
}
$scope.getUserName=function(review) {
UserFac.getUser(review.id).then(function(user) {
review.userName=user.data.userName;
review.showUserName=true;
});
}
})
HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="AllReviews">
<button ng-click="testClick()">Click here</button>
<ul ng-show="show" ng-repeat="review in reviews track by $index" ng-init="getUserName(review)">
{{review | json : spacing}}
<p ng-show="review.showUserName">
{{review.userName}}
</p>
</ul>
</body>
</html>
Explanation:
While iterating the review array in ng-repeat,we pass the review object to the UserFac service to fetch the userName.This service will set the name inside the review object itself.

Pass JSON to JQuery function Javascript

We have a very simpel Google Apps Script Web App, which purpose is to show JSON data in a HTML drop-down-list. The JSON file exists in Google Drive. Inspiration code from: http://jsfiddle.net/manoj_admlab/Mta5b/3/
But when we are trying to 'Fetch Json' no data is loaded in to the dropdown-list:
index.html
<!DOCTYPE html>
<html>
<br> <br>
<center>
<head>
<base target="_top">
</head>
<body>
<select id="destinations">
<option value="">Select</option>
</select>
Fetch JSON
</center>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
google.script.run.getJson(); // Runs the function "getJson();" in Code.gs
$('#fetch').click(function(s) {
$.post(s, {json: JSON.stringify(json)}, function(data) {
$.each(data.Destinations, function(i, v) {
$('#destinations').append('<option value="' + v.destinationID + '">' + v.destinationName + '</option>');
});
});
});
</script>
</body>
</html>
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile('index');
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
function getJson() {
var files = DriveApp.getFilesByName("jsonData.json");
var file = files.next();
var JSONDATA = file.getAs("application/json").getDataAsString();
//JSONDATA = JSON.stringify(JSONDATA);
JSONDATA = JSON.parse(JSONDATA);
Logger.log(JSONDATA);
click(JSONDATA); // <-- Trying to pass this data to "$('#fetch').click(function(s) {"
}
jsonData.json
{
"options": {
"Destinations": [
{
"destinationName": "London",
"destinationID": "lon"
},
{
"destinationName": "New York",
"destinationID": "nyc"
},
{
"destinationName": "Paris",
"destinationID": "par"
},
{
"destinationName": "Rome",
"destinationID": "rom"
}
]
}
}
You have to return the data in getJson() function, and when calling it, you need to pass a callback, with withSuccessHandler(), as such:
in HTML:
function justLog(e){
console.log(e);
}
$('#fetch').click(function(s) {
google.script.run.withSuccessHandler(justLog).getJson(); // Runs the function "getJson();" in Code.gs
});
in code.gs, finish the function with:
return JSONDATA;
Thanks Kriggs! This worked out great:
Index.html:
<!DOCTYPE html>
<html>
<head>
<select id="dropDownDest">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
function onSuccess(json) {
$.each(json.Cars, function (key, value) {
$("#dropDownDest").append($('<option></option>').val(value.carID).html(value.CarType));
});
$('#dropDownDest').change(function () {
alert($(this).val());
//Code to select image based on selected car id
});
}
google.script.run.withSuccessHandler(onSuccess)
.jsonData();
</script>
</head>
</html>
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function jsonData() {
var a = {
Cars: [{
"CarType": "BMW",
"carID": "bmw123"
}, {
"CarType": "mercedes",
"carID": "merc123"
}, {
"CarType": "volvo",
"carID": "vol123r"
}, {
"CarType": "ford",
"carID": "ford123"
}]
};
Logger.log(a);
return a;
}

How to add a todo from another Controller

I have a todo list in AngularJS that looks like this
.controller('TodoCtrl', function ($scope) {
$scope.todos = [
{text:'Ask smth on Stackoverflow', done:false},
{text: 'Resolve this', done:false}
];
$scope.getTotalTodos = function () {
return $scope.todos.length;
};
$scope.addTodo = function () {
$scope.todos.push({text:$scope.formTodoText, done:false});
$scope.formTodoText = '';
};
$scope.clearCompleted = function () {
$scope.todos = _.filter($scope.todos, function(todo){
return !todo.done;
});
};
})
And I would like to add a Todo (with a text, and a boolean 'done') from another controller that is launched when I click a button.
How can I do that ?
A big THANKS to who will help me
Typically services are used to pass information back and forth. Create a service and store your TODO list inside there. Inject that service into both controllers. Each controller can now act on the items in the list
I will append Scotts answer with some shorted Code.
Like he said, the best is to use a Service ;)
The Service:
.factory('todoService', function() {
var todolist = [];
return {
getTodoList: function() {
return todolist;
}
addTodo: function(todo) {
todolist.push(todo);
},
getTotalTodos: function() {
return todolist.length;
},
// some other
}
});
Now you can inject the service into any controller via
.controller('TodoCtrl', function ($scope, todoService)
and then you can call the functions of the service in the controller, e.g.
$scope.addTodo = function () {
todoService.addTodo({text:$scope.formTodoText, done:false});
$scope.formTodoText = '';
};
By using Angular Services:
I've made a simple demo.
Hope this helps.
(function() {
var app = angular.module("myApp", []);
// myService service.- This service contains an array, called «todos» wich contains data.
app.service("myService", function() {
return {
todos: [{
"text": "Ask smth on Stackoverflow",
"done": false
}, {
"text": "Resolve this",
"done": false
}]
};
});
// Add the dependecy in the controller.
app.controller("Controller", ["$scope", "myService",
function($scope, myService) {
$scope.title = "TODOS";
// This function returns the data stored in the service.
$scope.getTodos = function() {
return myService.todos;
}();
$scope.getTotalTodos = function() {
return myService.todos.length;
};
// This functions contains the object with the values from the form.
$scope.addTodo = function(model) {
myService.todos.push({
text: model.text,
done: model.done
});
$scope.model.text = "";
};
}
]);
})();
<html data-ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body data-ng-controller="Controller">
<h3>{{title}}</h3>
<form id="myForm" ng-submit="addTodo(model)">
<label>
Todo
<input type="text" data-ng-model="model.text" />
</label>
<br />
<label>
Done
<input type="checkbox" data-ng-model="model.done" />
</label>
<br/>
<button type="submit">Add</button>
<hr />
<ul>
<li data-ng-repeat="todo in getTodos">
{{todo.text}} ({{todo.done}})
<input type="checkbox" data-ng-model="todo.done" />
</li>
</ul>
</form>
</body>
</html>
Update: Using the service in multiple controllers.
(function() {
var example = angular.module("starter", [])
example.service("todoService", function() {
return {
todos: [],
addTodo: function($text, $classe) {
this.todos.push({
text: $text,
done: false,
});
}
};
});
example.controller('nationsLeaguesCtrl', function($scope, todoService) {
$scope.randomNationsLeagues = function() {
var text = "Text 1";
todoService.addTodo(text, null);
};
})
example.controller('statsCtrl', function($scope, todoService) {
$scope.randomStats = function() {
var text = "Text 2";
todoService.addTodo(text, null);
};
})
example.controller('specialCtrl', function($scope, todoService) {
$scope.randomSpecial = function() {
var text = "Text 3";
todoService.addTodo(text, null);
};
})
example.controller('TodoCtrl', function($scope, todoService) {
$scope.getTodos = function() {
return todoService.todos;
}();
$scope.getTotalTodos = function() {
return todoService.todos.length;
};
$scope.clearCompleted = function() {
$scope.todos = _.filter($scope.todos, function(todo) {
return !todo.done;
})
};
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="starter">
<button class="button button-full button-light" ng-controller="nationsLeaguesCtrl" ng-click="randomNationsLeagues()">Nations & Leagues</button>
<button class="button button-full button-light" ng-controller="statsCtrl" ng-click="randomStats()">Stats</button>
<button class="button button-full button-light" ng-controller="specialCtrl" ng-click="randomSpecial()">Special</button>
<div ng-controller="TodoCtrl">
<ul>
<li ng-repeat="todo in getTodos">{{todo.text}}
<input type="checkbox" name="checkboxG1" id="checkboxG1" ng-model="todo.done" class="css-checkbox" />
<label for="checkboxG1" class="css-label" style="font-family:checkboxFont; color:#ffffff;"><span class="done-{{todo.done}}"></span>
</label>
</li>
</ul>
</div>
</body>

ng-repeat working with array from JSON

I am having issues getting the ng-repeat to walkthrough my JSON response, I am new to AngularJS so I am sure its a newbie mistake :). I am trying to have the ng-repeat go through the ns0:AttributeDetails, ns0:Attributes. Here is the JSON data:
{"ns0:GetAgentProfile.Response": {
"xmlns:ns0": "http://URL",
"ns1:Header": {
"xmlns:ns1": "http://URL",
"xmlns:ns7": "http://URL",
"ns1:Source": null,
"ns1:CreatedDateTime": "2014-03-24T09:34:28.339-05:00",
"ns1:MessageType": "Request",
"ns1:MessageId": null
},
"ns0:ProfileDetails": {
"ns0:UserIdentifier": {
"ns0:UserGUID": "2BCF0074-392F-4653-8733-02063C2DBC5C",
"ns0:UserName": "Username01"
},
"ns0:AttributeDetails": {"ns0:Attribute": [
{
"ns0:Name": "AgentLogin",
"ns0:Value": ["Username01"]
},
{
"ns0:Name": "FullName",
"ns0:Value": ["Name, User"]
},
{
"ns0:Name": "LanguageSpoken",
"ns0:Value": ["English|Chinese"]
},
{"ns0:Name": "Supervisor"},
{
"ns0:Name": "Region",
"ns0:Value": ["Region01"]
},
{
"ns0:Name": "Country",
"ns0:Value": ["CO"]
},
{
"ns0:Name": "ClientAccessGroup",
"ns0:Value": ["CountryMobileCCR"]
},
{"ns0:Name": "Roles"}
]},
Here is the HTML:
<!DOCTYPE html>
<html ng-app="auth" xmlns="http://www.w3.org/1999/html">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script src="js/bootstrap.js"></script>
<script src="js/angular.js"></script>
<script src="js/authorization.js"></script>
</head>
<body ng-controller="MainCtrl">
<div>
<div class="container-fluid">
<form class="well">
<label>Username:</label>
<input><br><br>
<button ng-click="getData()" class="btn btn-primary">Submit</button>
<button ng-click="clearData()" class="btn btn-danger">Reset</button>
</form>
</div>
<h1>Response from Service:</h1>
<!-- <pre>{{data | json}}</pre> -->
<pre>
Username: {{data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails'] ['ns0:UserIdentifier']['ns0:UserName']}} <br>
Profile Details</pre>
<div ng-repeat="Attribute in data">{{ data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails']['ns0:AttributeDetails']['ns0:Attribute']['ns0:Name'] }}</div>
</div>
</html>
Here is the JS for the controller fetching the data:
var app = angular.module('auth', []);
app.factory('authService', function($http) {
var promise;
var authService = {
async: function() {
if ( !promise ) {
promise = $http.get('package.json').then(function (response) {
console.log(response);
return response.data;
});
}
return promise;
}
};
return authService;
});
app.controller('MainCtrl', function( authService,$scope) {
$scope.clearData = function() {
$scope.data = {};
};
$scope.getData = function() {
authService.async().then(function(d) {
$scope.data = d;
});
};
});
Again I apologize for the newbie question. Any assistance would be greatly appreciated.
Drill down to your array in the repeat directive:
<div ng-repeat="Attribute in data.ns0:GetAgentProfile.Response.ns0:ProfileDetails.ns0:AttributeDetails.ns0:Attribute">
And now you can do:
{{Attribute.ns0:Name}} and {{Attribute.ns0:Value}}
Not sure if the : will play nicely tho, may have to escape those.

Angularjs TypeError: undefined is not a function

I'm just starting to mess with angular js and I'm trying to load the data through a post action.
I'm using angularjs v.1.0.2
Here is my code:
HTML:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<script src="<?php echo $baseUrl?>/js/profilling/main.js"></script>
</head>
<body>
<div ng-controller="GroupsCtrl">
</div>
</body>
</html>
main.js:
function GroupsCtrl($scope, $http) {
$scope.url = '/file.php';
$scope.images = [];
function handleGroupsLoaded(data, status) {
console.log(data);
}
$scope.fetch = function () {
$http.post($scope.url).success($scope.handleGroupsLoaded);
}
$scope.fetch();
}
I'm trying to follow this jsfiddle: http://jsfiddle.net/simpulton/wHL3F/
But I'm getting the following error:
TypeError: undefined is not a function
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:92:92
at i (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:76:119)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:76:352
at Object.e.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:86:220)
at Object.e.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:84:198)
at Object.e.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:86:379)
at e (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:92:330)
at o (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:95:407)
at XMLHttpRequest.q.onreadystatechange (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js:96:334)
Can anyone help?
Thanks
EDIT
file.php:
echo '{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
';
It seems like a valid json object.
You just need to register the handleGroupsLoaded() in the $scope
function GroupsCtrl($scope, $http) {
$scope.url = '/file.php';
$scope.images = [];
$scope.handleGroupsLoaded = function(data, status) {
console.log(data);
}
$scope.fetch = function () {
$http.post($scope.url).success($scope.handleGroupsLoaded);
}
$scope.fetch();
}

Categories