How to access $scope object in factory using AngularJS? - javascript

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).

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);
}

how to pass params in remotefunction

I have a javascript function with remotefunction,,, in that remotefunction i want to pass map has parameter and i want to use that map variable in controller action,, i don't know how to pass that in params of ramotefunction and to use it in that particular controller action...
jQuery(document).ready(function(){
alert("checking for checkbox");
var countryId = document.getElementById("countryId").value;
jQuery('#groupdelete').on('click', function(){
var names = {};
alert("*********");
jQuery('input:checked').each(function() {
alert(jQuery(this).attr("id"));
if(jQuery(this).attr("id")) {
var id=jQuery(this).attr("id")
var costId = "c"+id
var ntb = document.getElementById(costId).value;
alert(ntb);
names[id] = ntb;
}
});
alert(names[1]);
})
${remoteFunction(action:'addLabServiceToCountry', controller:'country', params:'\'names=\'+names')}
})
params:'\'names=\'+names' which is not working properly, how to pass map variable in params of remotefunction and in contoller action how to access that.
Try this:
${remoteFunction({action: "addLabServiceToCountry", controller: "country", params: names});
Then in remoteFunction() you need to iterate through params to get all mapped names.
Or you can convert names to a string:
var namesStr = names.join(',');
and then pass the string:
${remoteFunction({... , params: namesStr});

Javascript and jQuery: accessing class member variables from event callback

I am writing a Javascript SDK to interact with a web service. I am using jQuery to do my AJAX calls.
When an AJAX call fails, I have registered an event handler for the ajaxError that gets called at the top of my .js file. My problem, and I don't understand why, is that when it gets called I have no way of accessing class member variables for my Akamanda.Client.
I tried adding another method for Akamanda.Client as .prototype.logError, which got called by the jQuery Ajax handler, but even then a test for (this.logging) failed as well.
How can I access class member variables from jQuery callbacks? What am I failing to understand here? Akamanda.Client.logging is undefined from the ajaxError callback.
My code for the SDK:
$(document).ajaxError(function(event, jqxhr, settings, exception) {
// more robust error handling for different conditions
if (Akamanda.Client.logging) {
console.log('FAILED: ' + settings.type + ' ' + settings.url + ' => ' + exception);
}
});
Akamanda.Client = function(options) {
this.URL = options.URL || 'http://m-test.akamanda.com';
this.baseURL = this.URL + '/api/' + Akamanda.API_VERSION;
this.feedsURI = '/websyndication/feed/';
// who is the client? (iphone/android/web)
this.clientName = options.clientName;
// For development: Logging and buildcurl IS ON, for production: OFF
//this.logging = options.logging || true;
this.logging = true;
// called when a user is not authorised (Disabled)
// this.logoutCallback = options.logoutCallback || null;
}
Akamanda.Client.prototype.getFeeds = function(callback){
var feeds = [];
$.getJSON(this.baseURL + this.feedsURI, function(data) {
$.each(data, function(index, feed) {
feeds[index] = {
name: feed.name,
title: feed.title,
link: feed.link
};
})
callback(feeds);
});//.error(function(err) { (disabled at the moment in favour of ajaxError event)
// console.log('Error: ' + err.error);
// });
}
My code for the client (in another JS source file):
var options = { logging: true };
myAPI = new Akamanda.Client(options);
var feeds = [];
var articles = [];
function getFeeds()
{
myAPI.getFeeds(function(AkamandaFeeds) {
feeds = AkamandaFeeds;
showFeeds();
});
}
As far as I can see from the code you posted, you are never instantiating an object of type Akamanda.Client.
var Client = new Akamanda.Client();
or
var Akamanda.Client = {};
Akamanda.Client.logging = ....
JSBin Example: http://jsbin.com/ajidig/1/edit
Ok, here a little example(real code but very simplified):
//we wrap our code in a self invoking function so that we don't pollute the global namespace, see http://stackoverflow.com/questions/6715805/self-invoking-functions-javascript for further details
(function(){
//create your object that holds all your function, that are different ways to do this
var Akamanda = {};
//a private function
function ErrorHandler(clientObj) {
this.clientObj = clientObj;
//do whatever with clientObj
this.log = function(){..}
}
//private constructor for clientobj
function Client(options){
..
}
Akamanda.Client = function(){
var newClient = new Client({..});
//setup
Akamanda.ErrorLogging = new ErrorHandler(newClient);
return newClient;
}
//bind our service to the window object to make it accesible
window.Akamanda = Akamanda;
})()
//client
var myAPI = Akamanda.Client();
Akamanda.ErrorLogging.log();
I hope this basic examples helps. If you need to know more about Javascript Patterns, I can recommend this book http://jsninja.com/ by John Resig, the creator of jQuery.
Depending on what you want to do, there's also a lot of frameworks like http://backbonejs.org/ that help with this kind of stuff.

Can't access properties of my Javascript object

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();
});

Uncaught TypeError: Object has no method ... Javascript

I'm having an issue where I get an error that says...
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
I'm really not sure what's causing this. The 'f771b328ab06' is a user ID in the error. I can add a new user and prevent users from being duplicated, but when I try to add their location to the list, I get this error.
Does anybody see what's going wrong? The error occurs in the else statement of the initialize function as well (if the user ID exists, just append the location and do not create a new user). I have some notes in the code, and I'm pretty sure that this is partly due to how I have modified an example provided by another user.
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:" );
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
Since I get the ID from the phone and do not need to generate it here (only receive it), I commented out the part that creates the random ID. In doing this, I had to add a parameter to the createUser method within Users() so that I can pass the ID as an argument from Initialize(). See the changes to createUser below:
Before, with the generated ID (the part where the number is generated is in the above code block with comments):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
After, with the ID passed as an argument:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
If anyone has any suggestions I would really appreciate it. Thanks!
Here you're getting user_id by :
var user_id = data[0];
So it's a part of the json answer : maybe a string or another dictionnary, this can't be a user object. You should try to update your code in your success function inside the "if" block by :
user = users.createUser(user_id);
//The following line is a non sense for me you put an int inside
//an internal structure of your class that should contain object
//users.users[user_id] = "1";
user.addLocation(latitude, longitude);

Categories

Resources