How to execute string as a function using AngularJS? - javascript

I have these two functions defined:
function fetchYPosts() {
$http.get("/postsY/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
};
function fetchXPosts() {
$http.get("/postsX/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
};
I am passed an id and a string ('X' or 'Y' is what I want the end-user to pass to me) from the front-end. I have this code which handles when the string is passed:
self.handler = function(id, XOrY) {
$http.post("/" + XOrY + "/" + id + "/handle/")
.then(function(response) {
functionToCall = "fetch" + XOrY + "Posts()";
# Here is where I want to call funcitonToCall.
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};
With that said, given a variable which holds a string, how do I call the function which has the name of the string variable?

You should select the correct method using something like this:
var fetcher = XOrY == 'x' ? fetchXPosts : fetchYPosts;
which can be used like:
self.handler = function(id, XOrY) {
var fetcher = XOrY == 'x' ? fetchXPosts : fetchYPosts;
$http.post("/" + XOrY + "/" + id + "/handle/")
.then(function(response) {
fetcher();
# Here is where I want to call funcitonToCall.
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};
If you have a situation where there's just too many different fetching functions, you can instead define them like this as part of a hash:
var fetch = {
YPosts: function() {
$http.get("/postsY/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
},
XPosts: function() {
$http.get("/postsX/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
}
}
and grab the function from fetch[XorY]:
self.handler = function(id, XOrY) {
$http.post("/" + XOrY + "/" + id + "/handle/")
.then(function(response) {
fetch[XorY]();
# Here is where I want to call funcitonToCall.
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};

you can encapsule these two function in an object, and call this service in your method like this
var service = {
fetchXPosts: function(){},
fetchYPosts: function(){}
}
self.handler = function(id, XORY) {
service['fetch'+XORY+'posts']();
}

Related

How can i use array of objects from database as filter?

// filter with data from database not working
app.filter('position', function($http, dbOperations) {
console.log(dbOperations.getAccessPosition());
var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}];
// get the object array from database with name and id
dbOperations.views("getPositions", "").then(function(res) {
positions = res; // this is the desired value: [{name:"cashier",id:1},{name:"operator",id:2}]
});
var poitionName = "";
return function(positionNum) {
positions.forEach(function(p) {
if (p.id == positionNum) {
poitionName = p.name;
return false;
}
});
return poitionName;
}
});
app.service('dbOperations', function($http) {
this.getAccessPosition = function() {
return $http({
method: "POST",
url: "/common/functions.php",
data: {
'process': "getAccessPosition",
'data': ""
}
}).then(function success(res) {
return res;
}, function myError(response) {
// console.log("Error");
});
}
});
When I console.log the positions, it prints the data that I need. but the filter is not working. maybe because the data is from database and it is waiting to respond. dbOperations is the in the service and I use $http.
Please help me with this. Thankyou.
In the service, just return the http request instead of unwrapping the promise.
app.service('dbOperations', function($http) {
this.getAccessPosition = function() {
return $http({
method: "POST",
url: "/common/functions.php",
data: {
'process': "getAccessPosition",
'data': ""
}
})
}
});
in the filter do the service call inside the callback function.
app.filter('position', function($http, dbOperations) {
console.log(dbOperations.getAccessPosition());
var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}];
var poitionName = "";
return function(positionNum) {
dbOperations.views("getPositions", "").then(function(res) {
positions = res.data;
positions.forEach(function(p) {
if (p.id == positionNum) {
poitionName = p.name;
return false;
}
});
return poitionName;
});
}
});

Is there any better way to display POST request in Angular Js

I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})

How to call nest factory in Angularjs?

Hi I am developing web application in angularjs. I have requirement below. I have one factory. I have added code snippet below.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', function ($http, $cookieStore, cfg, ScrollFunction, leaselisting) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
leaselisting.leaselisting().then(function (response) {
//Problem in calling
}, function (error) { });
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: "100"
},
headers: ScrollFunction.getheaders()
};
return $http(request);
}
return sadadpaymentapiobject;
}]);
Here is my second factory leaselisting
myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', function ($http, $cookieStore, cfg, ScrollFunction) {
var leaselistingobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
leaselistingobject.leaselisting=function(){
var requestObj = {
url: "api/ServiceRequest/GetROLSPSRLeaseList/",
data: {
LoginID: LoginID,
RSAccountNumber: $cookieStore.get("AccountNumber")
},
headers: ScrollFunction.getheaders()
};
$http(requestObj).then(function (response) {
}, function (error) {
});
}
return leaselistingobject;
}]);
I have found error in below line
leaselisting.leaselisting().then(function (response) { //Problem in calling
}, function (error) { });
May i am i doing anything wrong in the above code? May i know is it possible to call one factory from another? The response i get from leaselisting i want to pass it in callsadad function of sadadpaymentapi. So can someone hep me in the above code? I am getting error Cannot read property 'then' of undefined in the leaselisting.leaselisting().then(function (response) {},function(error){});
Also is there any way I can directly inject factory like payment amount: inject factory something like this?
I assume, that leaselistingobject.getValue is an asynchronous function.
So first of get your value :
leaselistingobject.getValue = function(){
var requestObj = {
url: "api/ServiceRequest/getValue/"
};
return $http(requestObj).then(function (response) {
return response.data;
});
}
And then use it. To let all async actions finish we use angulars $q.Here you can find a small tutorial.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', '$q',function ($http, $cookieStore, cfg, ScrollFunction, leaselisting, $q) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
var leastListingPromise = leaselisting.leaselisting();
var getValuePromise = leaselisting.getValue();
$q.all([leastListingPromise, getValuePromise]).then(function (responses) {
//Here you have both responses in an array
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: responses[1]
},
headers: ScrollFunction.getheaders()
};
return $http(request);
});
}
return sadadpaymentapiobject;
}]);
To make leaselisting() return the response of the request change the end of the function from
$http(requestObj).then(function (response) {
}, function (error) {
});
to
return $http(requestObj).then(function (response) {
return response.data;
}, function (error) {
});
If wont do anything about possible errors you can omit the error function part:
return $http(requestObj).then(function (response) {
return response.data;
});

on commenting one function code works, otherwise it fails

In my application when I am trying to copy one object its getting copied but if I am defining another function call, the code which was executing properly gives error, don't know why. Any help on this is highly appreciated, and thanks in advance
If I comment this function that._createCustomStore(data); everything works good, if I uncomment this it gives me error as Uncaught ReferenceError: _newParent is not defined on this line copiedParent = _newParent;
below is my code
_genericInnerCopy: function(_childObj) {
copiedParent = {};
that = this;
model = that.model;
var record = Ext.create(model, {
Name: _childObj.get('Name'),
//Parent: _newParent.get("_ref");,
});
record.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
console.log("Done");
//that._copyChild();
} else {
console.log("error");
}
}
})
that._all_pis.push(record);
copiedParent = _newParent;
var store = Ext.create('Rally.data.custom.Store', {
data: that._all_pis,
listeners: {
load: function(store,data,success) {
that._updateAll(store, data, copiedParent);
},
scope: that
},
});
//console.log("record values", that._all_pis);
},
_updateAll: function(store,data, copiedParent) {
that = this;
Rally.data.BulkRecordUpdater.updateRecords({
records: data,
propertiesToUpdate: {
Parent: copiedParent.get("_ref")
},
success: function(readOnlyRecords){
//all updates finished, except for given read only records
},
scope: that
});
that._createCustomStore(data);
},
_createCustomStore: function(data) {
me = this;
Ext.create('Rally.data.custom.Store', {
data: data,
//model: 'PortfolioItem/' + _newParent.get('PortfolioItemTypeName'),
autoSync:true,
listeners: {
load: function(store,data,success) {
console.log("store value", store);
console.log("data value", data);
console.log("success value", success);
},
scope: me
},
});
},
onqModelRetrieved: function() {
var that = this;
that._type = 'PortfolioItem/' + that._type,
Rally.data.ModelFactory.getModel({
type: that._type,
success: this.onModelRetrieved,
scope: this
});
},
onModelRetrieved: function(model) {
this.model = model;
this.createFeature();
},
createFeature: function() {
var record = Ext.create(this.model, {
Name: "(Copy of) " + this._newObj.get('Name'),
});
record.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
_newParent = result
Ext.Msg.alert('created ' + result.get('PortfolioItemTypeName') + ':', result.get('Name'));
}
else{
console.log("error");
}
}
});
}
});
Try define it and use it like this:
_newParent: null,
_genericInnerCopy: function(_childObj) {
copiedParent = {};
that = this;
model = that.model;
var record = Ext.create(model, {
Name: _childObj.get('Name')
//Parent: _newParent.get("_ref");,
});
record.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
console.log("Done");
//that._copyChild();
} else {
console.log("error");
}
}
})
that._all_pis.push(record);
copiedParent = that._newParent;
var store = Ext.create('Rally.data.custom.Store', {
data: that._all_pis,
listeners: {
load: function(store,data,success) {
that._updateAll(store, data, copiedParent);
},
scope: that
}
});
//console.log("record values", that._all_pis);
},
_updateAll: function(store,data, copiedParent) {
that = this;
Rally.data.BulkRecordUpdater.updateRecords({
records: data,
propertiesToUpdate: {
Parent: copiedParent.get("_ref")
},
success: function(readOnlyRecords){
//all updates finished, except for given read only records
},
scope: that
});
that._createCustomStore(data);
},
_createCustomStore: function(data) {
me = this;
Ext.create('Rally.data.custom.Store', {
data: data,
//model: 'PortfolioItem/' + _newParent.get('PortfolioItemTypeName'),
autoSync:true,
listeners: {
load: function(store,data,success) {
console.log("store value", store);
console.log("data value", data);
console.log("success value", success);
},
scope: me
}
});
},
onqModelRetrieved: function() {
var that = this;
that._type = 'PortfolioItem/' + that._type,
Rally.data.ModelFactory.getModel({
type: that._type,
success: this.onModelRetrieved,
scope: this
});
},
onModelRetrieved: function(model) {
this.model = model;
this.createFeature();
},
createFeature: function () {
var that = this;
var record = Ext.create(this.model, {
Name: "(Copy of) " + this._newObj.get('Name')
});
record.save({
callback: function (result, operation) {
if (operation.wasSuccessful()) {
that._newParent = result
Ext.Msg.alert('created ' + result.get('PortfolioItemTypeName') + ':', result.get('Name'));
}
else {
console.log("error");
}
}
});
}

How can i join two json objects together?

I have got a task to do user editing. I did this. But i cannot pass the value as json object. How can i join two values.
My first object is
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
else {
o[this.name] = this.value || '';
}
});
return o;
};
My second object is
var location = function() {
var self = this;
self.country = ko.observable();
self.state = ko.observable();
};
var map = function() {
var self = this;
self.lines = ko.observableArray([new location()]);
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.state() ? {
state: line.state().state,
country: line.country().country
} : undefined
});
alert("Could now send this to server: " + JSON.stringify(dataToSave));
};
};
ko.applyBindings(new map());
});
I want to concatenate this. I tried this but i got an error
$.ajax({
url: '/users/<%=#user.id%>',
dataType: 'json',
//async: false,
//contentType: 'application/json',
type: 'PUT',
data: {total_changes: JSON.stringify(dataToSave) + JSON.stringify($("#edit_user_1").serializeObject())},
//data:JSON.stringify(dataToSave),
//data:dataToSave,
success: function(data) {
alert("Successful");
},
failure: function() {
alert("Unsuccessful");
}
});
When i run this it shows an error like this in terminal.
How can i solve this?
If you have json1 and json2 objects you can do:
$.extend(json1, json2);
So in json1 you will get both objects merged.
The problem is JSON.stringify(…) + JSON.stringify(…). This will create a string like "{…}{…}" which obviously is invalid JSON (that's where you get the JSON::ParserError from).
I'm not sure what you are trying to accomplish and which JSON structure your server expects, but you could do something like
…
contentType: 'application/json',
data: JSON.stringify( {
total_changes: dataToSave,
edits: $("#edit_user_1").serializeObject()
}),
…

Categories

Resources