Angularjs ng-grid using Grails JSON data - json

Angular ng-grid data binding question
I have a Groovy/Grails application that has a domain “Grid” class for which I have registered a custom “marshaller” to produce the JSON that I can use for an Angularjs ng-grid..
Say “grid” is and instance of the Grid class,
“grid as JSON” produces the desired JSON.
I have a Grails/groovy controller that loads the data and returns the JSON:
def index() {
def grid = Grid.first()
grid as JSON
}
But I don’t know how to get this JSON data into the ng-grid in my GSP:
<body ng-controller="MyCtrl">
<script>
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
$scope.gridOptions = ${grid}; // NEED HELP HERE !
});
</script>
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
I don't know how to get the data into $scope.gridOptions. When I look at what is being generated with firebug, I see $scope.gridOptions is
{"columnDefs":[{"field": ...
which is the encoded JSON data. (The quotation marks are encoded). What is the best way to pass JSON data between a Grails back end and ng-grid in a JSP?

Thank you for the suggestion Sridhar, I started looking for ways to un-escape JSON within GSP, and I found the answer here:
how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag
I need to use the g:applyCodec tag in my GSP:
<g:applyCodec encodeAs="none">
$scope.gridOptions = ${grid};
</g:applyCodec>

Related

AngularJS: Dynamically load HTML tag retrieved from database

I am fetching the data from a JSON file using factory:
appService.factory('svr', ['$resource', function($resource) {
return $resource('data/:pageName.json', {}, {query:{method:'GET', isArray:true}});
}]);
and accessing it in controller:
appController.controller('requirementCtrl', ['$scope', 'svr', function($scope, svr){
$scope.ques = svr.query({pageName:'question'});
}]);
Data in the JSON file contains the label, four options and a type checkbox like value. I have to format it into an HTML tag using this data.
I find one way is to create an HTML tag in controller and bind it to div using ng-bind-html. Directives does not work as I have implemented ngRoute.
What's the best way to do it?
I think the solution is to "compile" your element like :
$compile(element.contents())(scope);
http://onehungrymind.com/angularjs-dynamic-templates/
Other solution maybe (By Ben Nadel): http://www.bennadel.com/blog/2449-directive-link-observe-and-watch-functions-execute-inside-an-angularjs-context.htm

Angular.js reading External JSON Address

Hey guys I am trying to use an EPA API that provides daily UV Index information in JSON.
The link I am trying to read at the moment is:
http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=callBackFn
If you open that link it shows valid JSON, but when I use it in my Angular.js code it does not read it, and my variable stays as unknown. My code is:
var tanApp = angular.module('tanApp')
.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.data = 'unknown';
$http.get('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=callBackFn').success(function(data){
$scope.data = data;
});
tanApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
My HTML code is {{data}}.
When I take out the "JSON" portion, it comes up as XML, since it is the default, and that is actually showing up, but I need it as JSON.
Can someone possibly get this to work or provide some help? I can offer bitcoin as a bounty.
Thanks!
The problem is that the URI you're using returns raw JSON instead of JSONP. You can either setup a server-side proxy or check with your API provider to see if there's a way to get a valid JSONP response.
If you can get valid JSONP, you will also have to setup a callback to handle the response.
In that case, reference the accepted answer for this question.
Have you tried this using $http.jsonp() instead of $http.get(). Also if your using $http.jsonp() then the callback should be set to "JSON_CALLBACK".
e.g.
$http.jsonp('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=JSON_CALLBACK')
.success(function(data){
$scope.data = data;
}

Requesting embedded JSON data for D3

For reasons I won't bore you with, ALL elements of my webpage must be embedded into one file.
Between the HTML header tags, I have valid JSON data declared:
<script type="application/json" id="data">
"name": "flare", "children":[{"name": "thing1", ... }]
</script>
Previously this data was written to a JSON file which was referenced by my D3 bar chart scripts as follows:
d3.json("data/file.json", function(root) {
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
});
I have been able to pass the embedded JSON to an object after following this thread:
Best practice for embedding arbitrary JSON in the DOM?
How can I now successfully pass this object to the D3 bar chart?
Parsing the embedded JSON object was the hard part, so you've basically got this one figured out. Once you have the embedded JSON parsed and passed to an Object, you can just start using that Object.
Building off of your example, say you had this JSON data embedded in your page:
<script type="application/json" id="data">
{"name": "flare", "children":[{"name": "thing1", ... }]}
</script>
Then instead of using
d3.json("data/file.json", function(root) {
...
}
just extract the body of the function you were using, and load the JSON object at the top:
var root = JSON.parse(document.getElementById('data').innerHTML);
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
...
The method described in the question you've linked to will work. Just call the variable whatever you're using in your D3 code, e.g.
var root = JSON.parse(document.getElementById('data').innerHTML);

Parse Json to use in a dojo widget?

I am newbie to dojo and json. I am trying to Query the server to get data as json and parse the result and use html template in a widget to display.
To test it I tried this.
require(["dojo/request", "dojo/dom", "dojo/dom-construct","dojo/_base/array", "my/widgets/", "dojo/domReady!"],
function(request, dom,domConst, arrayUtil, support){
// Load up our authors
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(LinksMap){
// Get a reference to our container
arrayUtil.forEach(LinksMap, function(List){
// Create our widget and place it
console.debug(LinksMap);
//var widget = new support(author).placeAt(authorContainer);
Not sure if I am doing it right. Is there anything I am misssing. I am following the example as provided here and building on it.
I think from the comments on your post you want to modified the deferred handling function to be
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(jsonResults){
console.log(jsonResults.Result)
});
The json you posted is an object with a property Result. The Result property contains an array of objects. Those objects then contain a property LinksMap which holds another object.

calling JSON webservice & using html

I've been using XML a lot lately but now I'm practicing with some JSON.
What I am trying to do is make a button and text box - so the user can type in a zip code and it will get the info for that zip code...
Using JSON from geonames.org
It's frustrating me trying to figure this out, I've found it easy when I was making my own files with XML but now I am trying to use an actual website and JSON.
Please show me how to do this! Would appreciate it! Thanks.
First of all HTML cannot process a json response from a server. You can send a get or post in json format to a server and get a json response back but you need something other than HTML to process that JSON message. Browsers can format and display XML but not JSON (they just display it as a string). The easiest way to do that in a browser is use JavaScript. For this I would recommend using the jquery library.
http://jquery.com
Here's an example of some jquery I used recently to process a returned JSON string.
$(document).ready(function() {
$(".img a").on("click", function(event) {
event.preventDefault();
var item;
if ((item= $(this).attr( 'href' ))=="saved") return false;
$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");
var action ="add";
jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
var result=data.result;
if (result=="saved") {
self.html("<div>Saved</div>");
self.attr("href","saved");
}
}, "json")
.error(function() {
alert("error: unable to contact web service");
});
});
});
The returned JSON string from this request is { result: saved }. So as you can see you access the associated array as part of the data object. In my case data.result provided me with the value of result from the json string.
Note my example is for using an anchor tag to pass a value to send in the webservice call. In your case you will need to use a form.
If you're using jeoquery then just look at the html source of UI sample. It's showing the same autocomplete box that you might be trying to implement no custom code to write to parse returned JSON. Below code should work for you:
<input class="input-large" id="city" type="text"/>
$("#city").jeoCityAutoComplete();