How to convert string into JSON data in view part of angularjs - angularjs

Hi I have this data in JSON form, and I want to convert this data of option into json so that i can call optionName, optionSubName in a view part of angularjs
[
{
"heading": "MakeUp Type / Selection",
"option": "{"optionName":"Bridal Makeup","optionSubName":"Engagement,Tika / Godh Bharai,Ring Ceremony","optionDesc":""}",
"values": null
},
{
"heading": "Makeup Type",
"option": "{"optionName":"Experienced","optionSubName":"","optionDesc":{"products":"Bobbie Brown,Makeup Forever and Premium Makeup Products","Makeup_Include":"Straightening,Blow Drys,Tong Curls,Updo's","Drapping":"Yes","Lashes":"Yes","Nail_Polish_Change":"Yes","Extension_Available":"Yes","Airbrush_Available":"Yes"}}",
"values": null
}
]
I have already tried this but this is not working by using ng-repeat i have using this {{data.option.optionName | JSON}} but this is not working in my view part of angularjs, Please help me out how to reach at my goal ?

Use AngularJS forEach:
angular.forEach(object, iterator, [context])
object: The object interate over.
iterator: The iterator function or the code.
context: Object to become context (using this) for the iterator function.
var app = angular.module('app', []);
app.controller('AppController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/array.json').success(function(data) {
$scope.array = data;
angular.forEach($scope.array, function(x){
console.log(x.optionName);
})
});
});
}
]);

Related

AngularJS $http.get JSON file returns undefined

I am trying to get data from a JSON file to display in my AngularJS app using $http.get(...). When I run an alert with JSON.stringify, the alert says 'undefined'. Here is my code:
JS
var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(data) {
alert(JSON.stringify(data.People));
$scope.peoples = data.People;
});
});
JSON
{
"People": [
{
"name": "Andrew Amernante",
"rating": 3,
"img": "http://www.fillmurray.com/200/200",
"Description": "Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes": [
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes": [
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
}
]
}
What am I missing?
Update: Here is my app in Plunker
The result is a response object (not the data itself). You can access the data as response.data
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(response) {
alert(JSON.stringify(response.data.People));
$scope.peoples = response.data.People;
});
});
you should not use dot operator with JSON.stringify since its just a string, change it as,
alert(JSON.stringify(data));
Here data is a JSON string not object, so you can not use data.People, instead you just need to pass data to JSON.parse.
var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(data) {
var response = JSON.parse(data);
$scope.peoples = response.People;
});
});
I checked with your json string and works using following code.
var json = '{"People": [{"name": "Andrew Amernante","rating": 3,"img": "http://www.fillmurray.com/200/200","Description": "Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage","Likes": ["Dogs","Long walks on the beach","Chopin","Tacos"],"Dislikes": ["Birds","Red things","Danish food","Dead Batteries"]}]}';
var response = JSON.parse(json);
$scope.peoples = response.People;

How do I get a single value from a json file using angular (without using ng-repeat)?

I have a json file with the following data:
{
"favicons": [
{
"36x36”: "36x36.png",
"48x48": "48x48.png",
"57x57": "57x57.png"
}
],
"header": [
{
"imageUrl": "logo.png",
"subTitle": “blah”,
"backgroundColor": "#c30909"
}
]
}
I'd like to retrieve the value of favicons.36x36 without using ng-repeat.
I have this in my app.controller:
app.controller('myCtrl', function($scope, $http) {
$http.get("data.json").then(function (response) {
$scope.faviconData = response.data.favicons;
})
});
Using {{faviconData}} in my HTML, I can output the entire array.
But {{faviconData.36x36}} results in a parse syntax error.
I have also tried faviconData[0].36x36 but this also results in an error.
Do this
{{faviconData[0]['36x36']}}

AngularJs Typeahead directive not working

I have a simple requirement wherein a list of users is displayed and display a search button on top to search for the users by name, something like a simplified LinkedIn Connections page.
My web app is developed on node.js but this one page has been developed on angular.js and for this search button, I have decided to use the typeahead directive. This is how the jade file looks like:
html(ng-app='geniuses')
head
title List All Geniuses!
link(href='//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css', rel='stylesheet')
script(src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js')
script(src="https://cdn.firebase.com/js/client/2.2.4/firebase.js")
script(src="https://cdn.firebase.com/libs/angularfire/1.1.2/angularfire.min.js")
script(src='js/listAllgeniuses.js')
body
div.container
div.page-header
h2 All Geniuses!
div(ng-app='geniuses',ng-controller='SearchAGenius')
input.form-control(placeholder='Genius',name='search-genius',ng-model="selected",typeahead="user for user in usersArr | filter:{'geniusid':$viewValue} | limitTo:8")
div(ng-app='geniuses',ng-controller='GetAllGeniuses')
ul
li(ng-repeat='user in users') {{ user.geniusid }}
The list of users are being fetched as an array from firebase. As you can see, the list of users is fetched using GetAllGeniuses controller and it works fine.. Here is the controller code:
(function (angular) {
var app = angular.module('geniuses', ["firebase"]);
app.controller('GetAllGeniuses', ["$scope", "$rootScope","$firebaseArray",
function($scope, $rootScope, $firebaseArray) {
var users = $firebaseArray(new Firebase("****));
$rootScope.usersArr = users;
$scope.users = users;
}
])
app.controller('SearchAGenius', ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.selected = '';
$scope.usersArr = $rootScope.usersArr;
}
])
}(angular));
This is how the data looks like(dummy):
[
{
geniusid: "new",
geniusname: ""
},
{
geniusid: "new",
geniusname: ""
},
{
geniusid: "news",
geniusname: ""
},
{
geniusid: "qazwsx",
geniusname: ""
}
]
I want to search using the geniusid (or name) in the search box... I have tried almost all ideas posted on the net but haven't been able to figure this out..
Any ideas would be appreciated.
Check out this Plunker I made using your demo.
A few things to note. You'll want to include Angular Bootstrap in your scripts and inject it into your module.
script(src='http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.min.js')
And
var app = angular.module('geniuses', ["firebase","ui.bootstrap"]);
Also, don't use $rootScope to pass data around. This is a prefect use for an angular service.
There's also no need to define ng-app everytime you're going to use angular.
Here's the rest of the plunker code that I modified to get this working.
html(ng-app='geniuses')
head
title List All Geniuses!
link(href='//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css', rel='stylesheet')
script(src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js')
script(src='http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.min.js')
script(src="https://cdn.firebase.com/js/client/2.2.4/firebase.js")
script(src="https://cdn.firebase.com/libs/angularfire/1.1.2/angularfire.min.js")
script(src="./app.js")
body
div.container
div.page-header
h2 All Geniuses!
div(ng-controller='SearchAGenius')
input.form-control(placeholder='Genius',name='search-genius',ng-model="selected",typeahead="user as user.geniusname for user in usersArr | filter:{'geniusid':$viewValue} | limitTo:8")
div(ng-controller='GetAllGeniuses')
ul
li(ng-repeat='user in users') {{ user.geniusid }}
And the JS
(function(angular) {
var app = angular.module('geniuses', ["firebase", "ui.bootstrap"]);
app.controller('GetAllGeniuses', ["$scope", 'GeniusFactory',
function($scope, GeniusFactory) {
$scope.users = GeniusFactory.users();
}
]);
app.controller('SearchAGenius', ["$scope", 'GeniusFactory',
function($scope, GeniusFactory) {
$scope.selected = '';
$scope.usersArr = GeniusFactory.users();
}
]);
app.factory('GeniusFactory', ["$firebaseArray", function($firebaseArray) {
//Create a users object
var _users;
return {
users: users
}
function users() {
//This will cache your users for as long as the application is running.
if (!_users) {
//_users = $firebaseArray(new Firebase("****"));
_users = [{
geniusid: "new",
geniusname: "Harry"
}, {
"geniusid": "new",
"geniusname": "Jean"
}, {
"geniusid": "news",
"geniusname": "Mike"
}, {
"geniusid": "qazwsx",
"geniusname": "Lynn"
}];
}
console.log(_users);
return _users;
}
}]);
})(angular);

AngularJS binding not occurring on page until a user action

I've got my first angular app which displays some data from a list via ng-repeat.
The controller for the view sets a few variables to scope - some directly in the function and another from an API call.
The data from the in function load is showing up in that ng-repeat. The data from the service call doesn't show up (debugging shows the function is being called and data returned and set in scope).
I've got a filter on and if I type anything in it then the data shows up. Or when I click to another view the data flashes onto the page briefly before it loads the new view.
Here is some view code (the items works, venues does not):
<div ng-repeat="item in items">
{{ item.firstName }}
</div>
<div ng-repeat="venue in venues">
{{ venue.details }}
</div>
And here is the controller (data is coming back from the call):
$scope.items = [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
];
var client = new WindowsAzure.MobileServiceClient("url", "key");
var query = client.getTable("venues").read().done(function (results) {
$scope.venues = results;
}, function (err) {
alert("Error: " + err);
});
I'm wondering if maybe the binding is happening before the data is returned from the API?
I added a div and this line into the function and it is printing the results to the page no issues:
document.getElementById("venueslist").innerHTML = JSON.stringify(results);
Thank you for reading.
Looking at your code client.getTable doesn't look like it is using any of angularJs $http or $timeout service. So you will have to wrap the assignment in scope.$apply() so that the $digest cycle is run and the bindings are updated in the view.
var query = client.getTable("venues").read().done(function (results) {
$scope.$apply(function () {
$scope.venues = results;
});
}, function (err) {
alert("Error: " + err);
});
Side note: why are you doing JSON.parse(JSON.stringify(results)), you can directly use results if it is a json object.

Sub-promises in AngularFire - selecting related children by ID?

I have a json collection I've uploaded to my firebase, the sites and tools are related via arrays located in the former that point to keys in the latter
"sites": {
"s001": {
"name": "ACT-105",
"description": "Intro Accounting",
"type": "course",
"thumbnail": "debate",
"toolCount": 4,
"tools" : ["t001","t002","t003"]
},
"s002": {
"name": "ART-201",
"description": "Pottery Lab",
"type": "course",
"thumbnail": "sculpture",
"toolCount": 4,
"tools" : ["t001","t002","t003","t004"]
},
"tools": {
"t001": {
"name": "main-tool",
"title": "Home",
"description": "Main tool",
"thumbnail": "home.jpeg"
},
"t002": {
"name": "announce-tool",
"title": "Announcements",
"description": "System Announcements",
"thumbnail": "announcements.jpeg"
},
I open a url and promise; then grab the current site and its array of related tools in an array, then open another promise to loop through and get all the related tools. From the alert, it appears to only grab one tool then quits.
angular.module("foo", ["firebase"]).
controller("MyCtrl", ["$scope", "angularFire", function($scope, angularFire) {
var dbRef = "https://sampledb.firebaseio.com";
var siteRef = new Firebase(dbRef + "/sites/s003");
var promise = angularFire(siteRef, $scope, "site", {});
var sitetools = [];
promise.then(function() {
sitetools = $scope.site.tools;
alert("tools " + sitetools);
}).then(function () {
var toolList = [];
for (var i=0;i<sitetools.length;i++)
{
alert("tool " + sitetools[i]);
toolList.push(getTool(dbRef,toolId));
}
$scope.tools = toolList;
});
}]);
var getTool = function(dbRef,toolId) {
var toolitem;
var toolRef = new Firebase(dbRef + "/tools/" + toolId);
alert(toolRef);
var promise = angularFire(toolRef, $scope, "tool", {});
promise.then(function() {
alert("found tool " + toolId);
toolitem = $scope.tool;
});
return toolitem;
};
The fiddle is here: http://jsfiddle.net/5n9mj/1/
First of all, you should have got the alerts (3 of them) since the iterations went as expected, but the return of the getTool() function is always null: it returns before the promise is resolved and local tooitem variable is not accessible anymore.
Remember that all Firebase calls are async. Also, this code:
var promise = angularFire(toolRef, $scope, "tool", {});
promise.then(function() {
alert("found tool " + toolId);
toolitem = $scope.tool;
}
will trigger race conditions: $scope.tool is bound with the Firebase and there is no guarantee that it would be bound in a specific order and if there will be enough processor time to push it into your array before another promise is resolved. That's why it's better to listen on the value change using Firebase reference than to use angularFire and explicitly bind it to the scope variable.
I think you overcomplicated the code a little bit, you don't have to create new Firebase references every time you are binding your scope variables (unless you're going to use the reference later) with angularFire: angulerFire can accept String url as it's first param.
http://jsfiddle.net/oburakevych/5n9mj/10/
If I were you I would wrap the Tool functionality into a directive with a separate controller, so that each tool will have it's own scope, something like this:
<ul ng-repeat="toolId in tools">
<li><tool tool-id="{{toolId}}"/></li>
</ul>
var promise = angularFire(siteRef, $scope, "site", {});
promise.then(function() {
$scope.broadcast("event:SITE_INITIALIZED");
});
.controller("MyCtrl", ["$scope", "angularFire", '$timeout', function($scope, angularFire, $timeout) {
$scope.$on("event:SITE_INITIALIZED", function() {
angularFire(siteRef + "/item/" + $scope.itemId, $scope, "item", {});)
});

Resources