Getting Json data in the Angularjs Scope - javascript

This is my first attempt at using Angularjs framework. I am trying to follow this example: http://jsfiddle.net/SAWsA/11/
I am successfully able to get the data in the Json format and it works fine.
json data:
[{"Activity_Matrix_ID":"163","Activity_ID":"131","Activity_Date":"2062-02-16","Activity_Category":"Maintanence","Activity_Project":"All Projects","Activity_Description":"Json data ","Activity_Hours":"2"},{"Activity_Matrix_ID":"161","Activity_ID":"129","Activity_Date":"2044-02-25","Activity_Category":"Tech Support","Activity_Project":"All Projects","Activity_Description":"Dummy dummy ","Activity_Hours":""}]
So basically, I want to load the data in $scope.items. I am not sure if it is the good method. I can visit the url and the data looks fine. I am stuck at getting the json correctly from the URL to the angular scope.
I tried following
<script type="text/javascript">
var sortingOrder = 'Activity_Projects';
</script>
<script>
function ctrlRead($scope, $filter) {
$scope.myData = function(item, event) {
var responsePromise = $http.get({method: 'GET', url: 'https://url_root_same_domain/timesheet/timesheet_info_table_json.php'}).success(function(data, status, headers, config) {
$scope.items = data;
console.log(data);
}).
error(function(data, status, headers, config) {
alert("No data");
});
}
</script>

Try this:
var responsePromise = $http.get('https://url_root_same_domain/timesheet/timesheet_info_table_json.php').success(...rest of your code here
The $http.get() function's first argument is a URL; not an object; and the method of a get call is already get, so you shouldn't have to do any other changes.

Related

$http call inside an ng-repeat

My web application uses AngularJS to display a list of data from an external API via an $http call. The data is fetched inside an ng-repeat by a function call.
HTML:
// 'events' does not hold all data; call getData() to get the full data
<div ng-repeat="event in events">
{{getFullEventData(event.key)}}
{{full_event_data.name}}
{{full_event_data.information}}
</div>
AngularJS controller:
// Fetch and store data in 'events' scope variable
$scope.events = ...
// Fetch and store data in 'full_event_data' scope variable,
// because 'events' does not have all the data for each event
var allEventData = [];
$http({
url: url,
method: "GET"
}).success(function(data, status, headers, config) {
allEventData = data;
}).error(function(data, status, headers, config) {
// ...
});
$scope.getFullEventData = function(key) {
for (var i = 0; i < allEventData.length; i++) {
var fetchedEvent = allEventData[i];
if (fetchedEvent.key === key) {
$scope.full_event_data = fetchedEvent;
}
}
}
However this does not print the event name and information in the HTML (these fields are just blank). I suspect that getFullEventData() is being called before the HTTP request has finished fetching the additional data. Can anyone advise?
Actually #charlietfl is correct, but the answer can be completed with more code.
The idea is fetching additional data and then merge them with existing data.
// Fetch and store data in 'events' scope variable
$scope.events = ...
var additionalData;
// Fetch full event data
$http({
url: url,
method: "GET"
}).success(function(data, status, headers, config) {
// assign additional data into events
additionalData = data; // keep a copy of data for future use
assignData(data);
}).error(function(data, status, headers, config) {
// ...
});
function assignData() {
angular.forEach($scope.events, function(event) {
// find matching fetched event for each event in $scope.events
var fetchedEvent = additionalData.find(function(item) {
return event.key === item.key;
});
if (fetchedEvent) {
// additional info is merged into original object
angular.extend(event, fetchedEvent);
}
});
}
<div ng-repeat="event in events">
{{event.name}}
{{event.information}}
</div>
Your function doesn't make much sense.
You should be able to simply do:
<div ng-repeat="event in data">
{{event.name}}
{{event.information}}
</div>
IMO, your requeseted data from $http doesn't notify the angular to trigger change detection. So when the data arrives, getFullEventData() will not be triggered at that moment.
You have to find a way to trigger detection. like $scope.$apply or $timeout.

Error in returning java object to javascript

I am returning a java object to client(javascript) page, i.e. converting java object to JSON object but am facing no converter found for return value error.
I have added all spring jars and jackson-all-xxx.jar.
The below is the method that gets called from a html page using $http.get('url').
#RequestMapping(value="/springAngularJS",method=RequestMethod.GET)
public #ResponseBody Person getPerson() {
System.out.println("111111111");
Person person = new Person();
person.setFirstName("Java");
person.setLastName("Honk");
return person;
}
My html page: (posting only JS part)
var app = angular.module('myApp', []);
function MyController($scope, $http){
$scope.getPersonDataFromServer = function() {
$http.get("springAngularJS").
success(function(data, status, headers, config) {
$scope.person = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
};
Any help to resolve this would be appreciated..
I am a beginner..:)
Your problem is with project dependency and not code , as the above code is correct .
Again I suggest on you to start with Spring-boot it will allow you to concentrate on the code only working example

AngularJS Form/HTTP/CORS

I have an Angular form connected to a REST API to insert a new row to a MySQL database. My REST API is working, but I am getting a CORS blocked notice in my web console. How can I get it to successfully send to the REST PI? Below is my controller code code:
countryApp.controller('AddLocation', function ($scope, $http) {
$scope.orglocation = {};
//
$scope.submit = function() {
var dataObj = {
location_title : $scope.location.location_title,
location_latitude : $scope.location.location_latitude,
location_longitude : $scope.location.location_longitude
}
//convert data to JSON string
var loc = JSON.stringify(dataObj);
$http.post('http://localhost/slimtest2/add_location', loc).
success(function(data, status, headers, config) {
alert("good");
}).
error(function(data, status, headers, config) {
alert("bye");
});
}
$scope.reset = function() {
$scope.location = angular.copy($scope.orglocation);
}
});
Generally when you hit a CORS problem it is a sign that your server is not configured correctly. I highly suggest looking at the MDN article on HTTP access control. The two headers that are most important to have in this case are:
access-control-allow-origin
access-control-allow-methods
Make sure the first is set to the domain and port you use to access your Angular app and that the second is set to the methods you use (in this case, at least POST).

How do I force $.getJSON to run before $http in Javascript?

I have the following Javascript code in the controller of my web page.
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
});
$http({
method: 'GET',
url: $scope.properties.Properties.dataLocation
}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
The structure of the json file to be fetched is not the problem.
It is supposed to first run the $.getJSON command and afterwards run the $http-request, since the $http request gets its url from the variable that is defined in the $.getJSON part at the top but instead when i do a console.log(properties) just below it, it spits out "undefined".
Why is the code not executing in the order that it is written?
The code is executing in order that it's written, just callback functions are being executed when the corresponding requests are complete. So you should put the second call in the first callback:
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
$http({method: 'GET', url: $scope.properties.Properties.dataLocation}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
});
It is executed asynchronous so both call will be done independantly.
$.getJSON has third parameter - success callback this is the way to sync those.
http://api.jquery.com/jquery.getjson/
Not sure why you are mixing jQuery AJAX and Angular $http ?
You could use the JQuery.done, which will execute your code after your request has finished.
Example:
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
})();
The same way that you have already got the line $scope.properties = data; to run after the JSON has been received. You put it in the callback function you pass to getJSON.
Why is the code not executing in the order that it is written?
It is.
getJSON(url, foo) means "Make an HTTP request to the url and set up an event handler to call foo when the response is received".
You seem to be expecting it to wait for the response before doing anything else. That would lock up the UI and be horrible.

When I “Pull to refresh”, How I clean the Cache? With Ionic Framework and AngularJS

I have a problem, I'm using a JSON coming from an external server, but when I do "Pull to refresh" or when I open the application, displays the same information I downloaded the first time the application is opened. It may be that the JSON is being stored in the cache and therefore not update? For if when I go to on-refresh = "doRefresh ()" and called another JSON, (the first time I do), update, but re-enter the application I load the information from the first JSON and if I want update, showing me the information I also downloaded the first time. This will fix manually deleting the application data, but it is not the best way ...
This is my services.js
angular.module('starter.services', ['ngResource'])
.factory('NotasService', ['$http',
function ($http) {
var items_nota = [];
var items_nota_array;
return {
all: function () {
return $http.get('http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30')
.success(function(data, status, headers, config){
console.log("**** SUCCESS ****");
console.log(status);
})
.error(function(data, status, headers, config){
console.log("**** ERROR ****");
console.log(status);
})
.then(function(response){
console.log("**** THEN ****");
items_nota = response;
return items_nota;
}
)
},
get: function (notaId) {
// Simple index lookup
var pepe = parseInt(notaId);
var ESTO = 0;
var addToArray = true;
for (var i = 0; i < items_nota.length; i++) {
if (items_nota[i].id == pepe) {
addToArray = false;
ESTO = i;
}
}
return items_nota[ESTO];
}
}
}])
This is my controller.js..
.controller('ActulidadCtrl', function ($q, $scope, NotasService, $timeout) {
var items_nota;
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Pull tu refresh
$scope.doRefresh = function () {
console.log('Actualizando!');
$timeout(function () {
//NotasService.loadData().then(function (data) {
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
})
Thanks! And Happy New Year!
UPDATE: solved the problem was in the server side cache
I think your problem is with GET query:
http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30
Please check if this query is returning same posts event if you add new data.You can make sample http query using tools like Postman.
post_status and posts_per_page are constant.
Please check. Good luck!!

Categories

Resources