AngularJS $scope is undefined outside of .then function - html

I have a a form which includes select input but the thing is ng-options is not working
Select code
<select ng-model="selectedGender" ng-options="item.value for item in genderData">
I got the data from
ReferenceService.searchCategory("GENDER").then(function (response){
$scope.genderData = response.data;
console.log($scope.genderData);
})
This is the console.log($scope.genderData)
Array(2)
0:{referenceId: 1, category: "GENDER", key: "GENDER_KEY", value: "Male", $$hashKey: "object:3"}
1:{referenceId: 2, category: "GENDER", key: "GENDER_KEY", value: "Female", $$hashKey: "object:4"}
length:2
__proto__
:
Array(0)
but I have tried hard coding the data
$scope.genderData= [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
];
and it worked! but I used ng-options="item.name for item in genderData">
btw don't mind the data I just searched it for fast use
EDIT:
I think I found the problem. Why is it undefined outside the function?
check this console
line 244 is undefined but line 242 is not?

store the response in var then out side the function assign that var to $scope. it is a callback issue.
If still it's showing same you can use localsorage to store and get the data. but this approach is not recomanded in angularjs. but if nothing happen then you can use this approcah also

That's because ReferenceService.searchCategory("GENDER") returns a promise.
A promise will wait until the data is resolved, and then move on to its success function callback. Which is the .then(function(response)).
So the code will get to the console.log on line 244 before the promise has finished, and $scope.genderData has been created and therefore is undefined
The console.log on line 242 will wait until the promise has been resolved, and calls the success callback function.
UPDATE:
Here an example how to correctly link the $scope to the factory.
Note that you must link to the object and not to its properties in your $scope.
Wrong:
$scope.gender = ReferenceService.data.genderData;
Correct:
$scope.gender = ReferenceService.data;
Example:
myApp.factory('ReferenceService',
function ()
{
var ReferenceService = {
// This is the global object. Link the $scope to this object
data: {
genderData: {}
},
searchCategory: function (type)
{
var getData = $http.get("URL", { params: { gender: type } }).then(
function (response)
{
// Store the data in the factory instead of the controller
// You can now link your controller to the ReferenceService.data
ReferenceService.data.genderData = response.data;
}
)
return getData;
}
}
return ReferenceService;
}
);
myApp.controller('MyController',
function ($scope, ReferenceService)
{
// Link $scope to data factory object
$scope.gender = ReferenceService.data;
// Now you only have to call the factory function
ReferenceService.searchCategory("GENDER");
// This will now log the correct data
console.log($scope.gender.genderData);
}
)

Related

Im trying to get values of the following JSON object and display them in html using angularness

In the following JSON object, I'm trying to get the value of the streets
Get business profile data :
{
"_id": "56dd1bd4d0561b403f683bfd",
"UserId": "56b301516b9064189049acb5",
"WebURL": "2",
"PhoneNumber": "3",
"ContactEmail": "1#gmail.com",
"AdditionalInfo": "",
"__v": 0,
"DateCreated": "2016-03-07T06:12:36.957Z",
"Categories": [],
"Addresses": [{
"Street": "1",
"City": "1",
"State": "1",
"Country": "1",
"SuiteNumber": "1",
"_id": "56dd1bd4d0561b403f683bfe"
}]
}
So far this is what I have:
Info.GetData()
.success(function (response){
$scope.Data = response;
})
.error(function (response, status) {
alert("Can Not Retrieve Company Info, Please Contact Admin")
})
<div ng-repeat="x in Data.Addresses">
{{x.Street}}
</div>
I still can't get it working.
Assuming your Info.GetData() is making a $http call and you are using success instead of then, you will still have to use then wherever there is a promise. If you are doing this
return
angular.module('app').factory('Info', function($http) {
return {
getData: function() {
return $http.get('url');
};
};
});
in your Info.getData(). You could instead do
return
angular.module('app').factory('Info', function($http) {
return {
getData: function() {
return $http.get('url').then(function(response)
{
return response.data;
}
};
};
});`
Also, you need to check if your service is returning a promise. If its a promise you should resolve it. You can't assume that your promise has a .success().

AngularJS getting in trouble with my JSON

I have got a JSON object from my website:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”},
}
and AngularJS to manage the dynamic content but it doesn't seem to be working:
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function () {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function (data, status) {
$scope.people = data;
});
};
}
Here is a JSFiddle.
Can anybody help me with displaying data?
#qqruza to get the callback working properly in your jsfiddle.net/1zuteco7, change the url to this:
http://test.eventident.com/api/last_posts/siteid=&callpage=1&perpage=10&callback=JSON_CALLBACK
Notice the JSON_CALLBACK in the end. The rest of your app will still not work though cause you are not picking the right bindings from the returned data in your repeat directive. Try console.log(data) in the success function to click through the returned object and get to the right paths.
There were a number of issues with your JSON, I have resolved them.
It had different types of quotes in there. I have replaced them with ".
It now looks like this:
[{         
"ID": "100",
"role": {            
"subscriber": true         
},
"first_name": "Test",
"last_name": "Test2",
"custom_fields": {            
"job_title": "subscriber"         
},
}, {   
"ID": "102",
"role": {            
"subscriber": true         
},
"first_name": "Test 3",
"last_name": "Test 4",
"custom_fields": {            
"job_title": "testing"         
},       
}]
Also, you were not referencing the model fields correctly in your view.
Here is the updated working fiddle: http://jsfiddle.net/kmmmv83y/1/
You had a comma at the end of the last property, that will typically error everything out, the below JSON should work:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”}
}

AngularJS display JSON data in table

I am using AngularJS with RESTAPI, I am able to get the customers data sent from server in a JSON format. My Angular code snippet as below:
app.factory("services", ['$http', function($http) {
var serviceBase = '/api/album';
var obj = {};
obj.getCustomers = function(){
return $http.get(serviceBase);
};
return obj;
}]);
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
});
Here is my JSON data:
{
"data": [
{
"id": "1",
"artist": "Gotye75",
"title": "Making Mirrors7"
},
{
"id": "100",
"artist": "ytttt5",
"title": "1231"
},
{
"id": "101",
"artist": "65",
"title": "565444555"
},
{
"id": "102",
"artist": "6",
"title": "6"
},
{
"id": "103",
"artist": "y",
"title": "yy"
},
{
"id": "104",
"artist": "ty",
"title": "yt"
},
{
"id": "109",
"artist": "ytrer",
"title": "yt"
}
]
}
I am able to display the JSON data in table if my JSON does not contain the "data" hear. However if my jSON data comes with "data" header, it is unable to display. I am asking, what are the solution in Angular to parse the JSON object.
For example if it is in BackboneJS, i can simply do
parse: function (response) {
//alert(JSON.stringify(response.data));
return response.data;
}
How can i do it in Angular?
$http resolves its promises with a response object. The data is accessed via the response object's data property. So to get to the array, you'd have to use
$scope.customers = data.data.data;
$http's promise is enhanced with a .success() convenience method which unwraps the response object...
services.getCustomers().success(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
I solved it by
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
//notice that i added the third data
$scope.customers = data.data.data;
});
});

How to get deeper in a JSON object using angularJS?

I am using AngularJs to get some information inside this JSON object, specifically the author's first and last name:
{
"bookid": "1",
"title": "Spring In Action",
"publisher": "Manning Publications Co.",
"isbn": "978-1-935182-35-1",
"owner": "Catalyst IT Services",
"publishyear": "2011",
"image": "C:/imagefolder/spring-in-action.jpg",
"description": "Totally revised for Spring 3.0, this book is a...",
"author": [
{
"authorid": "1",
"firstname": "Craig",
"lastname": "Walls",
"description": "Craig Walls has been professionally developing software for over 17 years (and longer than that for the pure geekiness of it). He is the author of Modular Java (published by Pragmatic Bookshelf) and Spring in Action and XDoclet in Action (both published by (...)"
}
],
"media": [
],
"tags": [
{
"tagid": "1",
"tagname": "Java"
},
{
"tagid": "5",
"tagname": "Spring"
}
],
"copies": [
{
"bookcopyid": "2",
"location": "Beaverton",
"status": "available"
}
]
}
The code I have right now is (which was provided by bosco2010 in this plunker (http://plnkr.co/edit/GbTfJ9)):
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL, scope) {
return $http.get(jsonURL).success(function (data, status) {
scope.data = data.author;
});
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
JsonSvc.read('data.json', $scope).then(function () {
$scope.nestedObj = $scope.data;
});
$scope.name = "world";
});
To get the first and last name, you'll need to reference author[0].firstname and author[0].lastname.
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL) {
return $http.get(jsonURL);
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
// The return object from $http.get is a promise. I used .then()
// to declare $scope.nestedObj after the http call has finished.
JsonSvc.read('data.json').then(function (data) {
console.log(data.data);
$scope.nestedObj = data.data.level1;
});
// ensure app is working
$scope.name = "world";
// Using nested obj within declared scope var doesn't work
// Uncomment below to break whole app
// Using nested obj in a function works but throws TypeError
// Declaring $scope.data.level1.level2 = [] first helps here
$scope.getLen = function () {
return $scope.nestedObj ? $scope.nestedObj.level2.length : ''; // return an empty string if the callback didn't happen yet
};
});
In short, it is incorrect to use both the success() function and also the then() function of the promise returned by the $htttp service.
Moreover, it is wrong to pass your scope as a parameter to your service and try to modify it there.
if you need to communicate between the service and a controller directly, you can use either $rootScope, $broadcat, or both.
I patched up your code, and now it works.
Plunk:
http://plnkr.co/edit/PlJZZn?p=preview

backbone collection fetch error

I'm trying to fetch a collection from a .json file. Here is my collection code
define(['jquery', 'underscore', 'backbone', 'vent'], function($, _, Backbone, vent) {
'use strict';
var Wine = Backbone.Model.extend({
urlRoot: "js/models/wines.json",
defaults: {
"id": null,
"name": "",
"grapes": "",
"country": "USA",
"region": "California",
"year": "",
"description": "",
"picture": ""
}
});
return Backbone.Collection.extend({
model: Wine,
url: "js/models/wines.json",
});
});
I'm fetching the collection like this:
var _wine = new wineCollection();
_wine.fetch({
success : function(data) {
console.log("ON SUCCESS");
console.log(data);
},
error: function(response) {
console.log("ON ERROR");
console.log(response);
}
});
In the console it's always showing the "ON ERROR" message:
ON ERROR
child
_byCid: Object
_byId: Object
_callbacks: Object
length: 0
models: Array[0]
__proto__: ctor
And here is one item of my wines.json file
{"id":"9","name":"BLOCK NINE","year":"2009","grapes":"Pinot Noir","country":"USA","region":"California","description":"With hints of ginger and spice, this wine makes an excellent complement to light appetizer and dessert fare for a holiday gathering.","picture":"block_nine.jpg"}
What am I doing wrong?
Have you tried inspecting the collection class in the fetch method (what is actually send over).
You might need to override the parse method in order to access an inner part of the data send over.
For instance:
Wine.Collection = Backbone.Collection.extend({
//we need to parse only the inner list
parse : function (response) {
this.cursor = response.cursor;
return response.list;
}
Where the array is an inner list: {list: [{item: one}, {item: two}]}