How to display JSON list data in angularjs - angularjs

I am new to Angularjs and having trouble displaying data . i.e. Json array
This is the result of my rest service call:
{
"users": [{
"id": 1,
"firstname": "Naveen",
"lastname": "Dutt",
"email": "navee23ndutt12.vyas#gmail.com",
"telephone": "7829418456445355"
}]
}
And this is my controller:
app.controller('MyCtrl2', ['$scope', 'NFactory', function ($scope, NFactory) {
alert("here??");
$scope.bla = NFactory.query;
alert("here??" + $scope.bla);
NFactory.get({}, function (nFactory) {
$scope.allposts = nFactory.firstname;
})
}]);
This is my html:
<div>
<ul >
<li ng-repeat="user in bla"> {{ user.firstname }} </li>
</ul>
</div>
but it doesnt show anything on UI. what can be the problem? please suggest.

It happens because you call async task. I would wrap result with promise.
Here is basic simulation of async call:
Demo Fiddle
var app = angular.module('myModule', ['ngResource']);
app.controller('fessCntrl', function ($scope, Data) {
Data.query()
.then(function (result) {
console.log(result);
$scope.bla = result.users;
}, function (result) {
alert("Error: No data returned");
});
});
app.$inject = ['$scope', 'Data'];
app.factory('Data', ['$resource', '$q', function ($resource, $q) {
var data = {
"users": [{
"id": 1,
"firstname": "Naveen",
"lastname": "Dutt",
"email": "navee23ndutt12.vyas#gmail.com",
"telephone": "7829418456445355"
}]
};
//Actually we can use $resource
//var data = $resource('localhost/shfofx/PHP/Rest/alertLossDetails.php',
// {},
// { query: {method:'GET', params:{}}}
// );
var factory = {
query: function (selectedSubject) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);

If $scope.bla in your case is
{"users":[{"id":1,"firstname":"Naveen","lastname":"Dutt","email":"navee23ndutt12.vyas#gmail.com","telephone":"7829418456445355"}]
then your template should look like this:
<ul >
<li ng-repeat="user in bla.users"> {{ user.firstname }} </li>
</ul>
Another way would be to change the code inside your Controller like this:
$scope.bla = NFactory.query.users;
and leave template as you have it.

If NFactory.query is string you need to parse it as JSON first.
$scope.bla=JSON.parse(NFactory.query);
and then
<ul >
<li ng-repeat="user in bla.users"> {{ user.firstname }} </li>
</ul>
Hope this will help...

Shouldn't it be a method call: NFactory.query() ?
Please show the NFactory source.
UPDATE: Try responding just array from server:
[{
"id": 1,
"firstname": "Naveen",
"lastname": "Dutt",
"email": "navee23ndutt12.vyas#gmail.com",
"telephone": "7829418456445355"
}]
and use NFactory.query()

Related

Angular.js How to render a HTML tag from json file

I am trying to parse html value in my angular page, not sure what I am doing wrong, I am getting this error in my console:
app.js:13 Uncaught SyntaxError: Unexpected token )
app.js
var App = angular.module('App', []);
App.controller('ProjectCtrl', function($scope, $http) {
$http.get('app/test.json')
.then(function(res){
$scope.projects = res.data;
});
App.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
});
test.json
[
{ "icon": "<i class="fa fa-github fa-3x" aria-hidden="true"></i>", "name": "lovelycss" },
{ "icon": "<i class="fa fa-github fa-3x" aria-hidden="true"></i>", "name": "lovely-icons" }
]
html:
<div ng-controller="ProjectCtrl">
<ul>
<li ng-repeat="project in projects">
<div ng-bind-html="'{{project.icon}}' | to_trusted"></div>- <em>{{project.name}}</em>
</li>
</ul>
</div>
what I am trying to archive is this: http://jsfiddle.net/JfGVE/1547/
I want a json loading the icons and the text.
I hope now this will be clear.
You are missing a } in your controller declaration and a [ in your filter declaration:
var App = angular.module('App', []);
App.controller('ProjectCtrl', function($scope, $http) {
$http.get('app/test.json')
.then(function(res){
$scope.projects = res.data;
});
}); // You are missing a '}' here
App.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]); // You are missing a ']' here
You will also have to edit your JSON to escape your quotes "
[
{
"icon": "<i class=\"fa fa-github fa-3x\" aria-hidden=\"true\"></i>",
"name": "lovelycss"
}, {
"icon": "<i class=\"fa fa-github fa-3x\" aria-hidden=\"true\"></i>",
"name": "lovely-icons"
}
]
And the expression you are passing to ng-bind-html is also wrong. Because of the single quotes ' you are passing a literal string '{{project.icon}}' to the filter. You have to remove the quotes and the curly braces, because the ng-bind-html directive needs an expression as a parameter.
<div ng-controller="ProjectCtrl">
<ul>
<li ng-repeat="project in projects">
<div ng-bind-html="project.icon | to_trusted"></div>- <em>{{project.name}}</em>
</li>
</ul>
</div>
The message tells you the problem: you have a syntax error. Two actually.
the function for your controller is not closed.
there is not closing bracket for the filter.
app.js
var App = angular.module('App', []);
App.controller('ProjectCtrl', function($scope, $http) {
$http.get('app/test.json')
.then(function(res){
$scope.projects = res.data;
});
}); // 1
App.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]); // 2
For JSON ERROR fix using this
[
{ "icon": "<i class='fa fa-github fa-3x' aria-hidden='true'></i>", "name": "lovelycss" },
{ "icon": "<i class='fa fa-github fa-3x' aria-hidden='true'></i>", "name": "lovely-icons" }
]

Parsing Json Array in AngularJS

Iam newbie in angularjs.How to display the json in html using angularjs.Below is the code
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope, $http) {
$http.get("http://localhost:8080/xyz").then(function (response) {
});
});
Reponse is :
[
{
"city": "animal"
},
{
"city": "bird"
}
]
In your controller you should assign your json to a scope:
app.controller('myctrl', function($scope, $http) {
$scope.myArray = [];
$http.get("http://localhost:8080/xyz").then(function (response) {
$scope.myArray = response;
});
});
Then in your view, you can do something like:
<div ng-controller="myctrl">
<ul ng-repeat="obj in myArray">
<li>{{obj.city}}</li>
</ul>
</div>
use ng-repeat like this.
<div ng-repeat="t in test">
<span>{{t.city}}</span>
</div>
plunker here
Use the following code this might help you.
myArray = JSON.parse(response);
for ( var index in myArray ) {
var singleObject = myArray[index];
var keys = Object.keys[singleObject];
for ( var j in keys ) {
console.log("Value of key"+j+"is"+keys[j]+"in Object"+index);
}
}
Here response is a string value.
Try this
Where Records is like this..
{"records":[{"ID":"235","user_id":"2","project_id":"186","project_cid":"2900669120142632939","imagePath":"media/pano/sv_02a29.jpg","ImageName":"1.jpg"},{"ID":"236","user_id":"2","project_id":"186","project_cid":"2900669120142632939","imagePath":"media/pano/sv_f0f59.jpg","ImageName":"253.jpg"},{"ID":"239","user_id":"2","project_id":"186","project_cid":"1997319193267363957","imagePath":"media/pano/sv_6536f.jpg","ImageName":"PANOCLOUD_meta.jpg"},{"ID":"240","user_id":"2","project_id":"186","project_cid":"6736594884768838469","imagePath":"media/pano/sv_898ca.jpg","ImageName":"Boscolo Hotel Budapest.jpg"}]}
$http.get("moderatorData.php").then(function (response) {
$scope.panoramas = response.data.records;
});
Then print using like this
<li class="align" ng-repeat="pano in panoramas>
<img ng-src="{{pano.imagePath}}" style="height: 90px;" />
</li>

Unable to print JSON object values in view.ejs when response from controller return JSON object when database call is made

I have JSON response from database query through controller and I would like to print this JSON object values in view.ejs file.
view.ejs
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.username}}</td>
<td>{{ x.password}}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("")
.then(function (response) {$scope.names = response.users;});
});
</script>
This is my Model
User.js
module.exports = {
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
username:{
type:'string',
required: true,
unique:true
},
password:{
type:'string',
required:true
},
}
};
This is my controller
UserController.js
module.exports = {
get:function(req,res){
User.find().exec(function (err, users){
if (err) {
return res.json(err);
}
return res.json(users);
});
}
};
I am configuring routes in below file
routes.js
module.exports.routes = {
'/': {
view: 'view'
},
'/user/get': 'UserController.get',
};
when I hit URL "http://localhost:1337/user/get", I get this below json response and I want this values to be pushed into view.ejs file.
[
{
"username": "root",
"password": "root",
"id": 1
},
{
"username": "home",
"password": "home",
"id": 2
},
{
"username": "unisys",
"password": "unisys",
"id": 3
}
]
I would like to know if somebody can help me to understand how i can get these values.Thank you for any suggestion
The problem in assigning names from response data. i.e,
use
$scope.names = response.data.users; OR $scope.names = response.data;
instead of
$scope.names = response.users;
In response itself you are getting array of objects so if you assign it directly to $scope.names , it will work.
if it helps you, just let me know .
$http.get("localhost:1337/user/get").then(function (response) {$scope.names = response;
console.log(response) ;
})

AngularJS Best Practices for modifying view

I currently have an Angular application with one module. This module defines a controller and a service. I'm currently using the service to update my view. Should services update view logic? Or should this be done in a separate Angular component?
index.html
<div ng-controller="AppController as AppCtrl">
<div id="grid1" ui-grid="{ data: myData }" class="grid"></div>
<button ng-click="AppCtrl.getPeople()" ng-model="AppCtrl.getPeopleButtonText" ng-bind="AppCtrl.getPeopleButtonText"></button>
<button ng-click="AppCtrl.clearPeople()">Clear</button>
{{AppCtrl.errorMessage}}
</div>
app.js
angular.module('app', ['ui.grid'])
.controller('AppController', ['$scope', "PersonService", function ($scope, PersonService) {
var controllerScope = this;
controllerScope.getPeopleButtonText = "Get People";
this.getPeople = function(){
PersonService.getPeople($scope, controllerScope);
};
this.clearPeople = function(){
PersonService.clearPeople($scope, controllerScope);
};
}])
.service("PersonService", ["$http", function($http) {
var refreshCount = 0;
this.getPeople = function(rootScope, controllerScope){
var sampleData = [
{
"firstName": "Cox",
"lastName": "Carney",
"company": "Enormo",
"employed": refreshCount%2 == 1
},
{
"firstName": "Lorraine",
"lastName": "Wise",
"company": "Comveyer",
"employed": refreshCount%2 == 0
},
{
"firstName": "Nancy",
"lastName": "Waters",
"company": "Fuelton",
"employed": refreshCount%2 == 1
}
];
$http.post("https://httpbin.org/post", sampleData)
.success(function(data){
rootScope.myData = JSON.parse(data.data);
refreshCount++;
controllerScope.getPeopleButtonText = "Refresh " + refreshCount;
controllerScope.errorMessage = "";
})
.error(function() {
controllerScope.errorMessage = "An error has occurred."
});
};
this.clearPeople = function(rootScope, controllerScope) {
rootScope.myData = [];
controllerScope.getPeopleButtonText = "Get People";
}
}]);
Is there a better way to structure this code?
Another approach I have read about was to create a ViewService and expose the ViewService into the root scope.
EDIT Nov 19
I'm using an Angular Promise to handle the success/error cases of a service call in a controller, rather than inside the service. This allows me to move view updates into the controller. Is this the right place to keep the view updates?
this.getPeople = function() {
PersonService.getPeople()
.then(function(data) {
$scope.myData = JSON.parse(data);
controllerScope.getPeopleButtonText = "Refresh";
controllerScope.errorMessage = "";
}, function(error) {
controllerScope.errorMessage = "An error has occurred."
});
};
Here's an example plnkr
http://plnkr.co/edit/tzuSX3aAcUqpH5bM7cIa?p=preview
Never use $rootScope to store data
Use the MVC pattern if you like, so:
One view, has one controller, has as many services as you need.
Your view shows data which are in the $scope
Your Controller is getting the data from your PersonService
The PersonService (or just the API service) gets the data from a backend.
Best practices would be like this (simplyfied):
Api.js
angular
.module( 'api', [])
.service('Api', Api);
Api.$inject = ['$http'];
function Api($http) {
var baseUrl = '/api/url/';
function getPersons() {
return $http({
method: 'GET',
url: baseUrl + 'YOUR/PERSON/URL'
});
}
return {
getPersons: getPersons
}
}
PersonController.js
angular
.module('personApp')
.controller('PersonController', PersonController);
PersonController.$inject = ['$scope', '$state', 'Api'];
function PersonController($scope, $state, Api) {
$scope.getPersons = function() {
Api.getPersons().then(function(response) {
$scope.persons = response.data;
}, function(error) {
// error message
});
};
}
Persons.html
<div ng-controller="PersonController">
<div id="grid1" ui-grid="{ data: persons }" class="grid"></div>
<button ng-click="getPersons()"></button>
</div>
Summary
Your view displays the data which is inside the $scope
The view has a controller, which is there for just getting the data and storing it in the $scope, providing the functions for the buttons
Your services are delivering the data to the controller

"Conroller as" with ng-repeat with array of objects (does not work with 'this')

I noticed that for me this shows nothing in ng-repeat:
<ul ng-controller="UserCtrl as ctrl">
<li ng-repeat="user in ctrl.users">
{{user.name}}
</li>
</ul>
But this, works ok:
<ul ng-controller="UserCtrl">
<li ng-repeat="user in users">
{{user.name}}
</li>
</ul>
Why is that?
My Controller code is simple as that:
angular.module('main.controllers').controller('UserCtrl', ['$scope', 'UserResource', function UserCtrl($scope, UserResource) {
$scope.users = UserResource.list(); // works with $resource service
// ideally I would like type "var users = ..." without using $scope
var ctrl = this;
this.users = function() {
return UserResource.list();
};
return this;
}
where users are json array of objects I'm eventually getting as resolved promise result:
[
{ id: "1", name: "name1" },
{ id: "2", name: "name2" },
{ id: "3", name: "name3" }
]
Update:
The whole point is that it does not work with this.users and controller-as notation when it is wrapped in promise that I'm getting from $resource service.
return $resource(' /rest/user-api/user/:id/:action',
{id: "#id"}, //parameters default
{
list: { method: "GET", params: {action : "list"}, isArray: true},
});
In you controller you've got
this.users = function() ..
so in you view you need to execute that function to get users
<li ng-repeat="user in ctrl.users()">
this.users should be rather array like in my demo this.users2 and in that case you can use it in repeater as
<li ng-repeat="user in ctrl.users2">
var app = angular.module('app', []);
angular.module('app').service("userService", function($timeout, $q) {
this.getData = function() {
var deffered = $q.defer();
$timeout(function() {
var arr = [{
id: 1,
name: "Jack from Service"
}];
deffered.resolve(arr);
}, 2000);
return deffered.promise;
};
return this;
});
angular.module('app').controller('UserCtrl', ['userService',
function UserCtrl(userService) {
// ideally I would like type "var users = ..." without using $scope
var ctrl = this;
ctrl.users = function() {
return [{
id: 1,
name: "Jack Function"
}];
};
ctrl.users2 = [{
id: 1,
name: "Jack Array"
}];
////// users from service
this.usersFromService = [];
function activate() {
userService.getData().then(function(data) {
angular.copy(data, ctrl.usersFromService);
});
}
activate();
return this;
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<ul ng-controller="UserCtrl as ctrl">
<li ng-repeat="user in ctrl.users2">
{{user.name}}
</li>
<li ng-repeat="user in ctrl.usersFromService">
{{user.name}}
</li>
</ul>
</body>
My answer is that:
When I do this:
<ul ng-controller="UserCtrl as ctrl">
<li ng-repeat="user in ctr.users">
It does not work.
When I do this:
<ul ng-controller="UserCtrl as userCtrl">
<li ng-repeat="user in userCtrl.users">
or UserCtrl as a or UserCtrl as b ... - it works.
I just does not like ctrl as a name.
Thanks to all who were not voting "close". I can NOT explain how it differs from that I got as replies. In my case I use end-to end angular - NodeJS application that actually does whole client-server communication. Not sure it matters.
Maybe it clashes with another scopes.. I'm not sure yet. But the general advice - try to change the name after "as" and see what happen If you have issue like that. I know it's weird.

Resources