Angular Js get Json not working - json

I'm trying to make a simple angular app which reads json data , but in response I'm only getting "," not data.Any pointers where I m going wrong ? I have attached index.html and abc.json file that i m keepingat server
PFB the code .
HTML:
<body ng-app="sampleApp" ng-controller="ctrl1">
Name:<input type="text" ng-model="name">
<ul>
<li ng-repeat="student in students | filter:name">{{student.name +","+student.empNo}</li>
</ul>
Name:<input type="text" ng-model="newname">
EmpNo:<input type="text" ng-model="newemp">
<input type="button" value="AddMe" ng-click="add()"/>
<div>
<div ng-view></div>
</div>
Javascript:
var x=angular.module('sampleApp',[])
.factory("simpleFactory",function($http){
var factory={};
factory.getStudents=function(){
return $http.get("abc.json");
}
return factory;
})
.controller("ctrl1",function($scope,simpleFactory){
$scope.students=simpleFactory.getStudents();
$scope.add=function(){
$scope.students.push(
{
name:$scope.newname,empNo:$scope.newemp
}
)
}
})
abc.json
[
{"name":"jack","empNo":"1"},
{"name":"Red","empNo":"2"},
{"name":"Jill","empNo":"3"}
]

getStudents is asynchronous. You should retrieve and assign students through the callback handler.
.factory("simpleFactory",function($http){
var factory={};
factory.getStudents = $http.get("abc.json");
return factory;
})
.controller("ctrl1",function($scope,simpleFactory){
simpleFactory.getStudents().then(function(result) {
$scope.students= result.data;
});
...
})

Nearly right. getStudents in fact returns you a 'Promise', not the data itself. You have to use that Promise to get your data:
simpleFactory.getStudents().then(function(data) {
$scope.students=data
// $scope.students=data.data // you may need this given your feedback
});

Related

How to delete and update data in json format using read and write property of Node.js in angular2 application

I have a json file in assets/json/abc.json
I have a requirement that I need to read /abc.json File from assets folder and write some data or delete some data from that /abc.json file according to an input value from a form in html.
I have tried but its not working.
Here, read/write/delete .json file is according to an input from user through a click event.
abc.json
[
{
"imgPath": "fa-users",
"dashboardName": "Command Center",
"urlToVisit": "dashboards/static/commandcenter"
},
{
"imgPath": "fa-tachometer",
"dashboardName": "HP Dashboard",
"urlToVisit": "dashboards/static/hpdash"
},
{
"imgPath": "fa-cube",
"dashboardName": "HP APJ",
"urlToVisit": "dashboards/static/hpapj"
}
]
abc.component.html
<form class="rmpm" (submit)="AddNewDashboardBox($event)">
<div class="form-group rmpm">
<div class='col-xs-12 rmpm'>
Enter Dashboard Name
<br>
<input type="text" class="form-control rmpm" placeholder="Dashboard Name" name="dashboardName"
required>
<br>
</div>
<div class='col-xs-12 rmpm'>
Enter Icon Name
<br>
<input type="text"class="form-control rmpm" placeholder="Icon Name" name="IconName"
required>
<br>
</div>
<div class='col-xs-12 rmpm'>
Enter Url Path to Visit
<br>
<input type="text" class="form-control rmpm" placeholder="Url Path" name="UrlPath"
required>
<br>
</div>
</div>
<button type="submit" class="btn btn-info">Add</button>
</form>
abc.component.ts
AddNewDashboardBox(e) {
e.preventDefault();
let dashboardNameInput = e.target.elements[0].value;
let IconNameInput = e.target.elements[1].value;
let UrlPathInput = e.target.elements[2].value;
var obj = {
table: []
};
var json = JSON.stringify(obj);
var fs = require('fs');
fs.readFile('assets/json/abc.json', 'utf8', function readFileCallback(err, data) {
if (err) {
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({ "imgPath": IconNameInput , "dashboardName": dashboardNameInput, "urlToVisit": UrlPathInput }); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('assets/json/abc.json', json, 'utf8');
}
});
}
The angular application is running on client browser and the file you want to change is residing on server. So this thing is not possible.
You will have to write an api to which angular will make rest call with new data and then that server will make the required changes in file on file (that is on server).
I recommend you to see the client server architecture for in depth details.

type error : Cannot read value 'name' of undefined

I'm working with Angularjs and firebase to create an app that is a task timer. I create the firebase object and all works fine except when I try to log task.newTask to the console. Here's a bit of my code (please note this is not all the code):
//HTML
<aside id="sidebar">
<section id="widget_1">
<h2 class="titles">Task History:</h2>
<input id="text-field" type="text" ng-model="taskText" />
<input id="task-button" type="button" value="Add Task" ng-click="addTask()" />
</section>
<section id="widget_2">
<h2 class="titles">Task List:</h2>
<table>
<tr ng-repeat="task in timer_tasks | orderBy: '-taskText'">
<td>{{ task.taskText }}</td>
</tr>
</table>
</section>
</aside>
//Controller:
(function() {
'use strict'
function HomeCtrl($scope, $firebaseArray, $interval) {
console.log('I see you home controller ... you are loaded sir!!!')
var timerRef = firebase.database().ref().child('timer_tasks');
$scope.timer_tasks = $firebaseArray(timerRef);
$scope.addTask = function () {
$scope.timer_tasks.$add({
taskText: $scope.taskText,
newTask: true
}).then(function (timerRef) {
$scope.taskText = '';
});
};
console.log(task.newTask);
On page load the error comes up at console.log(task.newTask);
Any help would be great. Thanks in advance!
If i'm understood correctly, you need to retrieve textbook value in controller which will build $scope.timer_tasks and later can be retrieved back to view in ng-repeat.
view
<aside id="sidebar">
<section id="widget_1">
<h4 class="titles">Task History:</h4>
<input id="text-field" type="text" ng-model="taskText" />
<input id="task-button"
type="button"
value="Add Task"
ng-click="addTask(taskText)"/>
</section>
</aside>
Script
myApp.controller('myCtrl', function($scope) {
$scope.addTask = function (value) {
console.log(" clicked : "+value);
};
});
All i did was bind the value upon addTask click from ng-model to ng-click and as you can see now you have that value in addTask function.

Angularjs convert string to object inside ng-repeat

i've got a string saved in my db
{"first_name":"Alex","last_name":"Hoffman"}
I'm loading it as part of object into scope and then go through it with ng-repeat. The other values in scope are just strings
{"id":"38","fullname":"{\"first_name\":\"Alex\",\"last_name\":\"Hoffman\"}","email":"alex#mail","photo":"img.png"}
But I want to use ng-repeat inside ng-repeat to get first and last name separate
<div ng-repeat="customer in customers">
<div class="user-info" ng-repeat="name in customer.fullname">
{{ name.first_name }} {{ name.last_name }}
</div>
</div>
And I get nothing. I think, the problem ist, that full name value is a string. Is it possible to convert it to object?
First off... I have no idea why that portion would be stored as a string... but I'm here to save you.
When you first get the data (I'm assuming via $http.get request)... before you store it to $scope.customers... let's do this:
$http.get("Whereever/You/Get/Data.php").success(function(response){
//This is where you will run your for loop
for (var i = 0, len = response.length; i < len; i++){
response[i].fullname = JSON.parse(response[i].fullname)
//This will convert the strings into objects before Ng-Repeat Runs
//Now we will set customers = to response
$scope.customers = response
}
})
Now NG-Repeat was designed to loop through arrays and not objects so your nested NG-Repeat is not necessary... your html should look like this:
<div ng-repeat="customer in customers">
<div class="user-info">
{{ customer.fullname.first_name }} {{ customer.fullname.last_name }}
</div>
This should fix your issue :)
You'd have to convert the string value to an object (why it's a string, no idea)
.fullname = JSON.parse(data.fullname); //replace data.fullname with actual object
Then use the object ngRepeat syntax ((k, v) in obj):
<div class="user-info" ng-repeat="(nameType, name) in customer.fullname">
{{nameType}} : {{name}}
</div>
My advise is to use a filter like:
<div class="user-info"... ng-bind="customer | customerName">...
The filter would look like:
angular.module('myModule').filter('customerName', [function () {
'use strict';
return function (customer) {
// JSON.parse, compute name, foreach strings and return the final string
};
}
]);
I had same problem, but i solve this stuff through custom filter...
JSON :
.........
"FARE_CLASS": "[{\"TYPE\":\"Economy\",\"CL\":\"S \"},{\"TYPE\":\"Economy\",\"CL\":\"X \"}]",
.........
UI:
<div class="col-sm-4" ng-repeat="cls in f.FARE_CLASS | s2o">
<label>
<input type="radio" ng-click="selectedClass(cls.CL)" name="group-class" value={{cls.CL}}/><div>{{cls.CL}}</div>
</label>
</div>
CUSTOM FILTER::
app.filter("s2o",function () {
return function (cls) {
var j = JSON.parse(cls);
//console.log(j);
return j;
}
});

Why is my attempt to fetch and show MongoDB documents in my Meteor app crashing?

I'm trying to fetch and display some MongoDB documents in my Meteor app. I am trying to use the docs here as a basis for this.
The HTM I've added is this:
{{> placesLived}}
. . .
<template name="placesLived">
<table style="width:60%">
{{#each places}}
<tr>
<td>{{ts_city}}</td>
<td>{{ts_state}}</td>
<td>{{ts_yearin}}</td>
<td>{{ts_yearout}}</td>
</tr>
{{/each}}
</table>
</template>
...so that the entire .html file is now this:
<head>
<title>timeandspace</title>
</head>
<body>
<h1>A List of the Places I Have Lived</h1>
{{> addTimeSpaceForm}}
{{> placesLived}}
</body>
<template name="addTimeSpaceForm">
<form>
<label for="city">City</label>
<input type="text" name="city" id="city">
<br/>
<label for="state">State</label>
<input type="text" name="state" id="state">
<br/>
<label for="yearin">Year Arrived</label>
<input type="text" name="yearin" id="yearin">
<br/>
<label for="yearout">Year Departed</label>
<input type="text" name="yearout" id="yearout">
<br/>
<input type="submit" name="insertdocument" id="insertdocument" value="Add Place Lived">
</form>
</template>
<template name="placesLived">
<table style="width:60%">
{{#each places}}
<tr>
<td>{{ts_city}}</td>
<td>{{ts_state}}</td>
<td>{{ts_yearin}}</td>
<td>{{ts_yearout}}</td>
</tr>
{{/each}}
</table>
</template>
The Javascript I've added is this:
Template.placesLived.helpers({
places: function () {
// this helper returns a cursor of all of the documents in the collection
return TimeAndSpace.find();
}
});
...so that the entire .js file is now this:
TimeAndSpace = new Mongo.Collection('timeAndSpace');
if (Meteor.isClient) {
Template.addTimeSpaceForm.events({
'submit form': function(event){
event.preventDefault();
var city = event.target.city.value;
var state = event.target.state.value;
var yearin = event.target.yearin.value;
var yearout = event.target.yearout.value;
Meteor.call('insertLocationData', city, state, yearin, yearout);
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
Meteor.methods({
'insertLocationData': function(city, state, yearin, yearout){
console.log('attempting to insert a record');
TimeAndSpace.insert({
ts_city: city,
ts_state: state,
ts_yearin: yearin,
ts_yearout: yearout
});
}
});
}
Template.placesLived.helpers({
places: function () {
// this helper returns a cursor of all of the documents in the collection
return TimeAndSpace.find();
}
});
My notion of what is supposed to happen here is that the "placesLived" template is added to the page, which template calls the "places" function in the js file -- which returns all the TimeAndSpace documents -- and finally the "placesLived" template loops through those returned documents, placing each field in a "td"
However, saving these changes (which restarts the Meteor app) wreaks havoc in the Meteor field: the command prompt cast the following aspersions (not to be confused with asteroids) on me:
The Meteor machine is obviously not amused. What have I fouled in my code / what needs to change?
Your helper is running on the client & server. Put an isClient around it & you'll be fine.
Anytime you get pretty purple/blue colors on the console it means something is wrong with your server. When it says Template is not defined that tells you the server can't find something called Template.

Unable to add value in string array in angularjs?

I'm trying to add value in students array, but below code isn't working.
js code is --
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.students=[
'Scarlett Johansson','Jennifer Lawrence','Emma Stone','Kristen Stewart'
];
$scope.add = function(name){
$scope.students.push(name);
};
}]);
html code is --
<body ng-app="formExample">
<div ng-controller="ExampleController">
<p ng-repeat="stud in students">
{{stud}}
</p>
</div>
<input type='text' ng-model="name"/>
<button ng-click="add(name);">add</button>
</body>
Your button and input are not included within the div ng-controller="ExampleController" scope.
<body ng-app="formExample">
<div ng-controller="ExampleController">
<p ng-repeat="stud in students">
{{stud}}
</p>
<input type='text' ng-model="name"/>
<button ng-click="add(name);">add</button>
</div> <!-- close div here -->
</body>
You need to push into $scope.students array, as there is no students array defined in the scope:
$scope.add = function(name) {
$scope.students.push(name);
};
$scope.add = function(name) {
$scope.students.push(name);//
};