AngularJS scope of variable [duplicate] - angularjs

This question already has answers here:
not able to access $scope object outside a http response callback function in angularjs
(3 answers)
Closed 5 years ago.
I'm trying to get a json file within a a controller with $http.get. All well until I try to access the property which holds the response. If I try console.log(property) inside the $http.get() it outputs the returned object, outside $http.get() accessing the very same property and it outputs undefined!
I even try to attache it to the $scope and it's the same result?!
angular.module('todayfmApp')
.controller('MainCtrl', ['$http', '$scope', function ($http, $scope) {
var self = this;
$http.get('data/form-data.json').then(function(response) {
self.formdata = response.data;
console.log(self.formdata);
});
console.log(self.formdata);
}]);
{
"settings": {
"version": "",
"Step": "",
"filterBreak": "",
"pid": ""
},
"category": [
{ "name": "Select All", "selected": true },
{ "name": "Carlow", "value": "Carlow" },
{ "name": "Cavan", "value": "Cavan" },
{ "name": "Clare", "value": "Clare" },
{ "name": "Cork", "value": "Cork" },
{ "name": "Derry", "value": "Derry" },
{ "name": "Donegal", "value": "Donegal" },
{ "name": "Down", "value": "Down" },
{ "name": "Dublin", "value": "Dublin" },
{ "name": "Galway", "value": "Galway" },
{ "name": "Kerry", "value": "Kerry" },
{ "name": "Kildare", "value": "Kildare" },
{ "name": "Kilkenny", "value": "Kilkenny" },
{ "name": "Laois", "value": "Laois" },
{ "name": "Leitrim", "value": "Leitrim" },
{ "name": "Limerick", "value": "Limerick" },
{ "name": "Louth", "value": "Louth" },
{ "name": "Mayo", "value": "Mayo" },
{ "name": "Meath", "value": "Meath" },
{ "name": "Monaghan", "value": "Monaghan" },
{ "name": "Offaly", "value": "Offaly" },
{ "name": "Roscommon", "value": "Roscommon" },
{ "name": "Sligo", "value": "Sligo" },
{ "name": "Tipperary", "value": "Tipperary" },
{ "name": "Waterford", "value": "Waterford" },
{ "name": "Westmeath", "value": "Westmeath" },
{ "name": "Wexford", "value": "Wexford" },
{ "name": "Wicklow", "value": "Wicklow" }
],
"num_nights": [
{ "name": "1 Night", "value": 1, "selected": true},
{ "name": "2 Nights", "value": 2 },
{ "name": "3 Nights", "value": 3 },
{ "name": "4 Nights", "value": 4 },
{ "name": "5 Nights", "value": 5 },
{ "name": "6 Nights", "value": 6 },
{ "name": "7 Nights", "value": 7 }
],
"num_rooms": [
{ "name": "1 Room", "value": 1, "selected": true },
{ "name": "2 Rooms", "value": 2 },
{ "name": "3 Rooms", "value": 3 },
{ "name": "4 Rooms", "value": 4 }
],
"num_adults": [
{ "name": "1 Adult", "value": 1 },
{ "name": "2 Adult", "value": 2, "selected": true }
],
"num_child": [
{ "name": "0 Kids", "value": 0, "selected": true },
{ "name": "1 Kids", "value": 1 },
{ "name": "2 Kids", "value": 2 }
]
}

In your case the problem is that $http.get response data is a late binding method. The response of this method will be available only after the service call is finished. This is an asynchronous method so that this will not be accessible inside scope as you expect. For that you need to bind your response inside a $scope variable and use it later inside a function call.
You will need to call the self.getResponseData method at first, say at the time of controller initialization. There after call a method self.logResponseData to log the response data.
You may need to change your calls something like this.
angular.module('todayfmApp')
.controller('MainCtrl', ['$http', '$scope', function ($http, $scope) {
var self = this;
// Get the response data with service call
self.getResponseData = function(){
$http.get('data/form-data.json').then(function(response) {
self.formdata = response.data;
console.log(self.formdata);
});
}
//Method to read the response data later
self.logResponseData = function() {
console.log(self.formdata);
}
//Call the method at the time controller loaded to initialize the `self` variable
self.getResponseData();
}]);

self.formdata = response.data.jsondatavariablename;
// Use the JSON data name

$http.get() is asynchronous which roughly means that when you call this it sends request and doesn't stop code on here to wait until it responded, next statements execution is continued though response is still hasn't come and you have no data from it. That's why you need callback function in .then() method, it is being called when you get your response, where you can use your response data. For example, you can assign it to some $scope property and it will update this value everywhere you use this property.
$http uses so called Promises to achieve this. I tried to make it simple but if you want know more detailed how it works, guess that's what will help you: Promise

Related

How to filter dimensional array in React

I have a dimensional array like this
{
"items": [
{
"id": "file",
"value": "File",
"childs": [
{
"value": "New",
"status": 1
},
{
"value": "New",
"status": 2
},
{
"value": "New",
"status": 1
}
]
},
{
"id": "file",
"value": "File",
"childs": [
{
"value": "New",
"status": 1
},
{
"value": "New",
"status": 2
},
{
"value": "New",
"status": 1
}
]
}
]
}
How to filter items and own childs by childs.status
You have to use filter method in order to filter your array of items based on specific test, in your case when status 3 has been found, Here is a working example:
var json = {
"items": [
{
"id": "file",
"value": "File",
"childs": [
{
"value": "New",
"status": 1
},
{
"value": "New",
"status": 2
},
{
"value": "New",
"status": 1
}
]
},
{
"id": "file",
"value": "File",
"childs": [
{
"value": "New",
"status": 1
},
{
"value": "New",
"status": 3
},
{
"value": "New",
"status": 1
}
]
}
]
};
var result = json.items.filter(function(item) {
item.childs = item.childs.filter( function (child) {
return child.status === 3;
});
return item.childs.length > 0;
});
console.log({items: result});
I've setup a repl in which i've drawn out the method to filter your json. You can find it here; feel free to play around with it.
#younel's answer mutates the original array, I've also updated my repl with his approach to show how the original json is mutated.
Essence
look through each item in items
if a child in item matches the filter criteria, then keep the item and the filtered children

DataTables - Load data from pre-defined JSON

I have a problem pointing dataTable to the right spot in the JSON. I receive a nested array:
{
"status": "ok",
"count": "7",
"msg ": "Operation Successful",
"data": [{
"contactHasServiceArea": true,
"issueCategories": [{
"id": "8",
"description": "Finance"
},
{
"id": "9",
"description": "Housing"
},
{
"id": "10",
"description": "International"
}
],
"cases": [{
"id": 31645,
"client_name": "Matthew",
"issue": "Assessment Completion",
"referral": null,
"opened_date": "10\/07\/2017",
"case_status": "Open"
}, {
"id": 31668,
"client_name": "Fanky ",
"issue": "Complex",
"referral": null,
"opened_date": "01\/07\/2017",
"case_status": "Open"
}]
}]
}
How do I point to the "cases" object? I'm sure this is simply, but I'm confused by the many options in the dataTables config.
I tried variations of data, dataSrc as well as data.cases or just cases, etc.
Thanks
$('#cases_table').DataTable( {
"ajax": "ajax/getCases",
"dataSrc" : "data.cases",
"data" : "cases",
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
You can configure like this:
$('#cases_table').DataTable( {
"ajax": {
"url": "ajax/getCases",
"dataSrc" : "data.cases"
},
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
datasrc points into the returns json. Remove the data option.

Underscore js to retrieve data from array

I'm assigned a task to get data using underscore js.
This is my JSON :
$scope.myData= {
"buslist":
{
"code":"1",
"message":"Success",
"fromStationCode":"71",
"searchResult": [
{
"arrivalTime": "17:00:00",
"availableSeats": "42",
"boardingPointDetails": [
{
"code": "1631",
"name": "Koyambedu",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Nerkundram",
"time": "09:45:00"
}
]
},
{
"arrivalTime": "18:00:00",
"availableSeats": "32",
"boardingPointDetails": [
{
"code": "2084",
"name": "Adyar",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Madurai",
"time": "09:45:00"
}
]
}
]
}
}
From this I want only "name" field. By doing this :
$scope.bdata = _.pluck($scope.myTest.buslist.searchResult, 'boardingPointDetails');
I got all "boardingPointDetails". The result looks like:
[ [
{
"code": "2084",
"name": "Adyar",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Madurai",
"time": "09:45:00"
}
],[
{
"code": "1631",
"name": "Koyambedu",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Nerkundram",
"time": "09:45:00"
}
],[
{
...
}
]
...
]
Help me to retrieve only "name" from this.
If you just want array of names like ['Koyambedu', 'Madurai'] then below code would work.
$scope.bdata = _.pluck($scope.myTest.buslist.searchResult, 'boardingPointDetails');
// Flatten the data.
$scope.flatbdata = _.flatten($scope.bdata, true);
$scope.flatbdata = $scope.flatbdata.filter(function(d){
return d != undefined && d.hasOwnProperty('name')
})
// map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results
$scope.names = $scope.flatbdata.map(function(d){
return d.name;
});
Refer below links :
http://underscorejs.org/#flatten
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
If you just want the array of names, here it is:
$scope.bdata = _.pluck($scope.myTest.buslist.searchResult, 'boardingPointDetails');
var res= _.flatten($scope.bdata);
res=_.pluck(res,'name');
console.log(res);
var temp = _.pluck(_.flatten($scope.bdata),'name')
temp will have ["Koyambedu", "Nerkundram", "Adyar", "Madurai"]
Try this.
$scope = {}; // in real project you don't need this. it's just for snippet.
$scope.myData = {
"buslist": {
"code": "1",
"message": "Success",
"fromStationCode": "71",
"searchResult": [{
"arrivalTime": "17:00:00",
"availableSeats": "42",
"boardingPointDetails": [{
"code": "1631",
"name": "Koyambedu",
"time": "09:30:00"
}, {
"code": "961296",
"name": "Nerkundram",
"time": "09:45:00"
}]
}, {
"arrivalTime": "18:00:00",
"availableSeats": "32",
"boardingPointDetails": [{
"code": "2084",
"name": "Adyar",
"time": "09:30:00"
}, {
"code": "961296",
"name": "Madurai",
"time": "09:45:00"
}]
}]
}
};
$scope.names = _.chain($scope.myData.buslist.searchResult).pluck("boardingPointDetails").flatten(true).map(function(item) {
return item.name;
}).value();
console.log($scope.names);
<script src="http://underscorejs.ru/underscore-min.js"></script>

Get dynamic key value from an array angularjs

I have a mongo collection called settings
{
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}
Note: the values provided in my mongo is only for reference purpose.
Now I have generated an array with the records in settings collection
self.sample = function() {
self.settingsObj = {}
// console.log(self.settings)
_.each(self.settings, function(settings) {
//_.each(self.settings, function(settings) {
if (!self.settingsObj[settings.type]) {
self.settingsObj[settings.type] = []
}
self.settingsObj[settings.type] = settings.list
})
console.log(self.settingsObj)
}
When I console the settingsObj I get result like this in my console
Object {subject: Array[2], exam: Array[2]}
Now I want to loop this inside a scope variable
$scope.search = [{
"name": "",
"data": ""
}]
inside this name i want to get the object name in this situation subject,exam and inside loop i want to loop the arrays for subject and exam.
I tried another ._each, and I got the key and value but how can I loop them correctly.
Otherwise please help me in generating subject and exams as different array
I'm not very sure if I understand your question.
But if I see well you're using a Lodash.js library so I provide below script using a lodash:
I assume that you have settings variable like this:
var settings = [ {
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
,
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}];
And I create functions for process those settings:
function createSearch(settings){
return _(settings).flatMap(toSearchArray).value();
}
function toSearchArray(setting){
return _(setting.list).map("name").map(toSearchObject).value()
function toSearchObject(data){
return {
name: setting.type,
data: data
}
}
}
And when you call createSearch(settings)
you will receive this result:
[
{
"name": "subject",
"data": "Maths"
},
{
"name": "subject",
"data": " Physics"
},
{
"name": "exam",
"data": "Reading"
},
{
"name": "exam",
"data": "Fluency"
}
]
Hopefully this is what you need.

Sugar CRM 6.5 API

I am new to the Sugar CRM 6.5 API. I am having trouble getting my url to post data to the leads module in Sugar. Here is the posting url,
https://yoursite/service/v4_1/rest.php?method=set_entry&input_type=JSON&response_type=JSON&rest_data={"name_value_list":{"last_name":"Peter","status":"New","email1":"test#test.com","lead_source":"test"},"module_name":"Leads"}
Here is my response,
{
"id": "459bf4a2-0b3b-5857-feb5-56fe81e621eb",
"entry_list": {
"modified_by_name": {
"name": "modified_by_name",
"value": "admin"
},
"id": {
"name": "id",
"value": "459bf4a2-0b3b-5857-feb5-56fe81e621eb"
},
"name": {
"name": "name",
"value": " "
},
"date_entered": {
"name": "date_entered",
"value": "2016-04-01 14:10:12"
},
"date_modified": {
"name": "date_modified",
"value": "2016-04-01 14:10:12"
},
"modified_user_id": {
"name": "modified_user_id",
"value": "1"
},
"created_by": {
"name": "created_by",
"value": "1"
},
"deleted": {
"name": "deleted",
"value": 0
},
"full_name": {
"name": "full_name",
"value": " "
},
"do_not_call": {
"name": "do_not_call",
"value": false
},
"converted": {
"name": "converted",
"value": false
},
"lead_source": {
"name": "lead_source",
"value": "Web Site"
},
"status": {
"name": "status",
"value": "New"
},
"jjwg_maps_lat_c": {
"name": "jjwg_maps_lat_c",
"value": 0
},
"jjwg_maps_lng_c": {
"name": "jjwg_maps_lng_c",
"value": 0
}
}
}
When I view the leads, I get a blank record created. Any idea's, Thanks
The format of name_value_list is as follow:
{
"name_value_list":
"full_name": {"name": "full_name", "value": "John"}
}

Resources