Can't access properties of my Javascript object - javascript

I'm using Angular.js to fetch a single record from my API. I'm getting the record back as an object, I can log the object and see it's properties but I cannot access any of the properties. I just get undefined.
var template = Template.get({id: id});
$scope.template = template;
...
console.log(template); // displays object
console.log(template.content); // undefined
UPDATE
var id = $routeParams.templateId;
var template = Template.get({id: id});
$scope.template = template;
/*** Template placeholders ***/
$scope.updatePlaceholders = function () {
var placeholders = [];
var content = template.content;
console.log(template); // dumps the object in the screenshot
console.log("content" in template); // displays false
// get placeholders that match patter
var match = content.match(/{([A-z0-9]+)}/gmi);
...
}
$scope.$on('$viewContentLoaded', function(){
$scope.updatePlaceholders();
});

You need to wait for your HTTP request to complete, then specify what to do in the callback. In this case I've taken it a step further and added a listener to your template object so there's no callback dependency between updatePlaceholders and your resource.
var id = $routeParams.templateId;
var template = Template.get({id: id}, function(res) {
$scope.template = template;
});
/*** Template placeholders ***/
$scope.updatePlaceholders = function () {
var placeholders = [];
var content = $scope.template.content;
console.log($scope.template);
console.log("content" in $scope.template);
// get placeholders that match patter
var match = content.match(/{([A-z0-9]+)}/gmi);
...
}
$scope.$watch('template', function(newValue){
if(newValue) $scope.updatePlaceholders();
});

Related

how to store array value in angularjs and then redirect

$scope.messagearray = {};
$scope.messagewant = function(info) {
$scope.messagearray = info;
$location.path("/messagewant");
}
my code is redirecting without storing value in array
The code can be modified like this. Now info is passed to new location via query parameters.
$scope.messagearray = {};
$scope.messagewant = function(info) {
$scope.messagearray = info;
$location.path("/messagewant?info="+info);
}

Parse.com Javascript update value by objectID

I try to update a value in my Parse.com Core, but it simply does not work.
I have the "objectID" of the item that i want to update
Parse.initialize("xxxx", "xxxx");
var PP = Parse.Object.extend("PP");
var PP = new PP();
var query = new Parse.Query(PP);
query.equalTo("objectId", "3Enwfu0QPQ");
query.first({
success: function (PP) {
PP.save(null, {
success: function (PP) {
PP.set("free", "100");
PP.save();
}
});
}
});
i want to set the value of "free" for object "3Enwfu0QpQ" to 100, but it does not work.
There's several issues with your code:
1.
var PP = Parse.Object.extend("PP");
var PP = new PP();
According to your screenshot, the Class is named "P", not "PP". You are also overriding the PP object.
2.
var query = new Parse.Query(PP);
query.equalTo("objectId", "3Enwfu0QPQ");
query.first({[...]});
query is invalide because PP is no longer the PP object. You should also use query.get instead of equalTo.
3.
PP.save(null, {
success: function (PP) {
PP.set("free", "100");
PP.save();
}
});
You are saving an empty object then editing this same object, then you update it again.
Your code should look like this (untested).
Parse.initialize("xxxx", "xxxx");
var P = Parse.Object.extend("P");
var query = new Parse.Query(P);
query.get('3Enwfu0QPQ', { // we get the object
success: function (instance) {
instance.set("free", "100"); // We update the returned object
instance.save(); // we save it
}
});
You can also save a request by doing so:
Parse.initialize("xxxx", "xxxx");
var P = Parse.Object.extend("P");
var instance = new P();
instance.id = '3Enwfu0QPQ';
instance.set("free", "100");
instance.save();

How to access $scope object in factory using AngularJS?

I have serialize method for post , So riskAssessmentKey is not part of $scope.topRiskDTO but i pass the riskAssessmentKey value from $scope.riskAssessmentDTO.riskAssessmentkey and now i am posting to factory but when i save all values are posting but riskAssessmentKey is coming undefined i dont know why..
So far tried code....
parentCtrl.js
$scope.addTopRisk = function(){
topRiskGridConfig.topRiskmodalWinConfig.title = 'Add top Risk';
$scope.viewTopRiskWin.setOptions(topRiskGridConfig.topRiskmodalWinConfig);
$scope.$broadcast('addTopRisk',$scope.riskAssessmentDTO.riskAssessmentKey);
};
childCtrl.js
$scope.topRiskDTO = {};
$scope.issuePltDataSource = kendoCustomDataSource.getDropDownDataSource('RA_KY_CNCRN_IS_PLTFM');
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
});
};
});
factory.js
var serializeTopRisk = function (topRisk,id) {
var riskAssessmentKey = id;
var objToReturn = {
topRiskName: topRisk.topRiskName,
mitigationActivityDes: topRisk.mitigationActivityDes,
issuePltfLookUpCode: topRisk.issuePltfLookUpCode,
issueNo: topRisk.issueNo,
riskAssessmentKey: topRisk.riskAssessmentKey
};
if(topRisk.riskAssessmentKey){
objToReturn.riskAssessmentKey = topRisk.riskAssessmentKey;
}
return objToReturn;
};
saveTopRisk: function(topRisk,id) {
var request = serializeTopRisk(topRisk);
console.log('request payload', JSON.stringify(request));
console.log('ID :: ', id);
var endpoint = 'app/assessment/rest/addTopRisks';
return $http.post(endpoint, request);
}
You forgot to pass the id to the serializeTopRisk function.
So you already pass the params correctly this this:
saveTopRisk: function(topRisk,id) {
var request = serializeTopRisk(topRisk);
But then serializeTopRisk should also get the id
var serializeTopRisk = function (topRisk, id) { // added the id over what you originally had
var riskAssessmentKey = $rootScope.riskAssessmentDTO.riskAssessmentKey; // drop this, use id instead
Don't use rootScope to pass data between the factory and the controller if you don't need to (it looks like you are already passing values to the factory from the controller by supplying it with object inputs, keep it that way and drop the rootScope usage from the factory).

Reading unlabelled JSON arrays

I am trying to pull data, using JQuery, out of an unlabelled array of unlabelled objects (each containing 4 types of data) from a JSON api feed. I want to pull data from the first or second object only. The source of my data is Vircurex crypto-currency exchange.
https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC
By 'unlabelled' I mean of this format (objects without names):
[{"date":1392775971,"tid":1491604,"amount":"0.00710742","price":"40.0534"},{ .... }]
My Javascript look like this:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
$.each(data, function(key,obj) {
var ticker1tid = obj[1].tid;
var ticker1amount = obj[1].amount;
var ticker1date = obj[1].date;
var ticker1price = obj[1].price;
});
});
Somehow I am not calling in any data using this. Here is link to my sand-box in JSFiddle: http://jsfiddle.net/s85ER/2/
If you just need the second element in the array, remove the traversing and access it directly from the data:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
var ticker1tid = data[1].tid;
var ticker1amount = data[1].amount;
var ticker1date = data[1].date;
var ticker1price = data[1].price;
// Or isn't it better to just have this object?
var ticker = data[1];
ticker.tid // 1491736
ticker.amount // 0.01536367
// etc
});

Accessing Data from JavaScript Object's Array Member Variable

I'm writing a jQuery plugin for work which pulls in RSS feed data using Google's Feed API. Using this API, I'm saving all of the relevant RSS feed data into an object, then manipulating it through methods. I have a function which is supposed to render the RSS feed onto the webpage. Unfortunately, when I try to display the individual RSS feed entries, I get an error. Here's my relevant code:
var RSSFeed = function(feedTitle, feedUrl, options) {
/*
* An object to encapsulate a Google Feed API request.
*/
// Variables
this.description = "";
this.entries = [];
this.feedUrl = feedUrl;
this.link = "";
this.title = feedTitle;
this.options = $.extend({
ssl : true,
limit : 4,
key : null,
feedTemplate : '<article class="rss-feed"><h2>{title}</h1><ul>{entries}</ul></article>',
entryTemplate : '<li><h3>{title}</h3><p>by: {author} # {publishedDate}</p><p>{contentSnippet}</p></li>',
outputMode : "json"
}, options || {});
this.sendFeedRequest = function() {
/*
* Makes the AJAX call to the provided requestUrl
*/
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
// Save the data in a temporary object
var responseDataFeed = data.responseData.feed;
// Now load the data into the RSSFeed object
self.description = responseDataFeed.description;
self.link = responseDataFeed.link;
self.entries = responseDataFeed.entries;
});
};
this.display = function(jQuerySelector) {
/*
* Displays the RSSFeed onto the webpage
* Each RSSEntry will be displayed wrapped in the RSSFeed's template HTML
* The template markup can be specified in the options
*/
var self = this;
console.log(self);
console.log(self.entries);
};
};
$.rssObj = function(newTitle, newUrl, options) {
return new RSSFeed(newTitle, newUrl, options);
};
// Code to call the jquery plugin, would normally be found in an index.html file
rss = $.rssObj("Gizmodo", "http://feeds.gawker.com/Gizmodo/full");
rss.sendFeedRequest();
rss.display($('div#feed'));
Obviously, my display() function isn't complete yet, but it serves as a good example. The first console.log() will write all of the relevant data to the console, including the entries array. However, when I try to log the entries array by itself, it's returning an empty array. Any idea why that is?
I guess the problem is that display() is called without waiting for the AJAX request to complete. So the request is still running while you already try to access entries - hence the empty array.
In order to solve this you could move the call to display() into the callback of $.getJSON(). You just have to add the required selector as a parameter:
this.sendFeedRequest = function(selector) {
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
var responseDataFeed = data.responseData.feed;
...
self.entries = responseDataFeed.entries;
self.display(selector);
});
};
EDIT:
If you don't want to move display() into the callback, you could try something like this (untested!):
var RSSFeed = function(feedTitle, feedUrl, options) {
...
this.loading = false;
this.selector = null;
this.sendFeedRequest = function() {
var self = this;
self.loading = true;
$.getJSON(this.encodeRequest(), function(data) {
...
self.loading = false;
if (self.selector != null) {
self.display(self.selector);
}
});
};
this.display = function(jQuerySelector) {
var self = this;
if (self.loading) {
self.selector = jQuerySelector;
}
else {
...
}
};
};

Categories

Resources