AngularJS - Sharing Data between controllers from json - json

actually I get stucked since several days with following problem. I like to create a small app which loads data from a json file. The app should consist of 3 views !
Show a list of data
Edit view for changing current data
add view to store new data
Now I learned to use a service which provides data to each controller for each view.
But for the time my service works only with generated data within my variable thing.
How Can I change this that my service will provide data from .json file which may be edited and updated with any controller !
Thanks
Here is my code and plnker
<!doctype html>
<html ng-app="project">
<head>
<title>Angular: Service example</title>
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script>
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : [{"DATE" : "2014","IATA":"DUS","DUTY":"10:12"},
{"DATE" : "2015","IATA":"MIA","DUTY":"10:12"},
{"DATE" : "2017","IATA":"JFK","DUTY":"10:12"}]
};
/*
return {
thing:[function($http) {
return $http.get('data.json').then(function(response) {})
return response.data;
}]
};
*/
});
function FirstCtrl($scope, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
}
function SecondCtrl($scope, theService) {
$scope.someThing = theService.thing;
$scope.name = "Second Controller!";
}
</script>
</head>
<body>
<div ng-controller="FirstCtrl">
<h2>{{name}}</h2>
<div ng-repeat="show in thing">
<p>
<b>DATE </b>{{show.DATE}}
<b>IATA </b>{{show.IATA}}
<b>DUTY </b>{{show.DUTY}}
</p>
</div>
<div ng-controller="SecondCtrl">
<h2>{{name}}</h2>
<div ng-repeat="edit in someThing">
<p>
<input ng-model="edit.DATE"/>
<input ng-model="edit.IATA"/>
<input ng-model="edit.DUTY"/>
</p>
</div>
</div>
</body>
</html>

All you have to do is use $http service and return it:
getJson: function() {
return $http.get('data.json')
}
Then in your controller you use it like this:
service.getJson(function(data) {
$scope.thing = data;
})
To convert object to json you need to use angular.fromJson i angular.toJson
Angular Docs
After that you do:
$http.post('yourjson);
to replace your current json (save changes).
You should also redownload it (to have everything in sync) using $http.get as I described above.
I have found an example example. I hope it helps.

Related

Show MongoDB info in HTML

I'm working on a website using a MEAN stack, and now I am trying to show some MongoDB data in my HTML pages by using Angular. But I don't seem to get it done.
This is the data in MongoDB I want to show in my HTML
{
"badkamer" : {
"block1" : {
"title" : "Badkamer",
"content" : "string"
}
}
}
This is the Angular function retrieving the data:
app.controller('cityCtrl', function($scope,$http){
$scope.specials = function(){
$scope.special = [];
$http.get('/specialdata').then(function(d){
$scope.special = d.data;
console.log(d.data);
},function(err){
console.log(err);
});
};
});
This is where I want it to show in my HTML:
<div ng-controller="cityCtrl" ng-init="specials()" ng-bind="special">
<div class="title">{{special.badkamer.block1.title}}</div>
<p>{{special.badkamer.block1.content}}</p>
</div>
</div>
When i console.log(d.data), I get this:
[Object]
0: Object
badkamer: Object
block1: Object
content: "Text",
title: "Badkamer"
But when I try it like this, the bind option shows all the data at once in my HTML. How can I get it working by using the Angular {{}} tags?
From the console.log, you can see that its an array, so you will need to use index, like this,
<div ng-controller="cityCtrl" ng-init="specials()" ng-bind="special">
<div class="title">{{special[0].badkamer.block1.title}}</div>
<p>{{special[0].badkamer.block1.content}}</p>
</div>
</div>
or change the code in controller.,
$scope.special = d.data[0];

html entities decode angular

I am trying to decode html entities in Angular, and seen some solutions for some strings with Sanitize, but I have a lot of JSON documents in my db with that I need sanitized. How can I do this? Right now my html shows the full
<h2>Badkamer</h2>
inclusive the tags.
This is a part of my json document
{
"badkamer" : {
"content" : "<h2>Badkamer</h2>"
<p>text</p>
}
}
This is my angular controller
app.controller('DataCtrl', ['$sce', function($scope,$http,$sce){
$scope.specials = function(){
$scope.special = [];
$http.get('/specialdata').then(function(d){
$scope.special = d.data[0];
console.log(d.data);
},function(err){
console.log(err);
});
};
}]);
This is the page where I show my data from MongoDB
<div class="align-content-inner">
<div>
{{special.badkamer.content}}
</div>
</div>
You need to include angular-sanitize.js script in HTML, and ngSanitize module on your app.,
Like :
var app = angular.module('myApp', ['ngSanitize']);
and use ng-bind-html directive.., like:
<div ng-bind-html="special.badkamer.content"></div>
See this demo plunker.

Grails - splitting raw json into an object

I am trying to receive json from a url and then display it in a g:select on my page and everything seems to work fine except that each object is displayed as raw json (e.g. {id=1, regionCode=EC, regionName=EasternCape} instead of proper objects with 'id', 'name', etc. Here's the json I'm trying to split:
[{"regionCode":"EC","regionName":"Eastern Cape","id":1},
{"regionCode":"FS","regionName":"Free State","id":2},
{"regionCode":"GA","regionName":"Gauteng","id":3},
{"regionCode":"KZN","regionName":"Kwa-Zulu Natal","id":4},
{"regionCode":"LI","regionName":"Limpopo","id":5},
{"regionCode":"MP","regionName":"Mpumalanga","id":6},
{"regionCode":"NW","regionName":"North West","id":8},
{"regionCode":"NC","regionName":"Northern Cape","id":7},
{"regionCode":"WC","regionName":"Western Cape","id":9}]
Here's the service I'm using to receive the above json:
class GetRegionService {
def getRegion(){
try{
//I'm not using the actual URL in this example
def regionList = new JsonSlurper().parseText(new URL('http:url/regions/list/ZA/').text)
return regionList
}catch (all){
all.printStackTrace()
return false
}
}
}
Here's how my controller that puts the json on the gsp page:
class MainController {
def getRegionService
def index() {
def regions = getRegionService.getRegion()
[regions: regions]
}
}
And here's the html snippet where the select is displayed:
<div class="jumbotron">
<label for="setRegion" style="margin: 0 10px 0 50px">Region: </label>
<g:select name="setRegion" from="${regions}"/>
</div
I figured it out. The problem was in my html. The select is supposed to look like this:
<g:select name="setRegion" from="${regions}" optionValue="regionName" optionKey="regionCode"/>
Looking at this from three years later, I'd take another approach. I haven't tested this or anything, I'm just adding this here in case anyone else ever finds themselves in the same situation:
<html>
<head></head>
<body>
<!-- Stuff here -->
<select id="setRegion" name="setRegion"></select>
<!-- More stuff here -->
<script>
$(document).ready(function() {
$('#setRegion').html('').append(
$('<option/>').text('-- Select Region')
);
JSON.parse('${regions}').forEach(function(region, i) {
$('#setRegion').append(
$('<option/>').attr({ value:region.regionCode }).text(region.regionName)
);
});
});
</script>
</body>
</html>
And seeing as nobody else has tried to answer this question, I guess I'll have to give myself the "accepted answer" xD

Kendo MVVM Binding to Self Executing Anonymous Module Function

I'm working with the Kendo UI MVVM and I'm trying to bind it to a self executing anonymous modular function. Long story short, it's only kind of working. The module is being updated if I inspect the page but the UI isn't. All I'm using is a short HTML file with a script tag to wire up the MVVM and an external JavaScript file to bring the module in.
HTML and JS on page
<!-- Adding information -->
<input data-bind="value: DemoField" />
<!-- Update Button -->
<button data-bind="events: { click: updateModule }">Update</button>
<!-- Trying to update this field -->
<input data-bind="value: module.Model.Demo.DemoField" />
<!-- Observable -->
<script type="text/javascript">
var model = kendo.observable(
{
DemoField: "",
updateModule: function () {
module.updateInformation({
demoField: this.get("DemoField")
)};
}
},
module
);
kendo.bind($("#form"), invoiceModel);
</script>
Module JS file
var module = (function () {
// private information
var _demo = (function () {
var _demoObject = {},
_demoField = null;
Object.defineProperty(_demoObject, "DemoField", {
get: function () { return _demoField; }
});
_demoObject.updateInformation = function (updatedObject) {
if (updatedObject.demoField) {
_demoField = updatedObject.demoField;
}
};
return _demoObject;
}());
var _model = { Demo: _demo };
// public information
return {
Model: _model
updateInformation: _demo.updateInformation
}
}());
If I enter "module.Model.Fields.FieldName" in the inspector, I see the information I'm expecting, but the UI just isn't playing nice. I've been to many pages on Telerik's website and I've consulted Google, but typically my searches yield little to no results and the results I do get are less than useful.
My thoughts are that kendo won't observe a module like it would a regular property, but then again I haven't worked with any kind of JS module before and I'm very new to MVVM.
Your thoughts are correct. Kendo will not observe a nested property, even if it is not nested you always have to use "get" and "set" words, for reference in Angular you don't need to do that.
So your code should look something like that:
<input data-bind="value: DemoField" />
<!-- Update Button -->
<button data-bind="events: { click: updateModule }">Update</button>
<!-- Trying to update this field -->
<input data-bind="value: updatedValue" />
And the view Model:
var model = kendo.observable({
DemoField: "",
updateModule: function () {
module.updateInformation({
demoField: this.get("DemoField")
});
this.set("updatedValue", module.Model.Demo.DemoField);
},
updatedValue: "",
});
kendo.bind($("#form"), model);
Here is a link to dojo with working example:
http://dojo.telerik.com/UzUhi

Hidden fields without a form in MVC

I have a table and no form in one page that I am working with.
Is there any way to persist certain values to that html without creating a form. I will not be submitting from this page in any specific way.
<!DOCTYPE html>
<html>
<head>
<title>Show All Encounters</title>
</head>
<body>
<div class="content-wrapper clear-fix float-left" style="height: 1px; padding: 10px;" id="list1">
#{
Html.Hidden("popId", TempData["POPULATIONID"], new { id = "hidPopID" });
Html.Hidden("popId", TempData["POPNAME"], new { id = "hidpnID" });
Html.Hidden("popId", TempData["ROWNUM"], new { id = "hidrownumID" });
}
<table border="2" id="frTable" class="scroll"></table>
<div id='pager'></div>
</div>
</body>
</html>
<script>
function loadDialog(tag, event, target) {
//debugger;
.load($url)
.dialog({
...
, close: function (event, ui) {
debugger;
//if($url.contains)
var popId = $('#hidPopID').val();
var rows = $('#hidrownumID').val();
location.reload(true);
}
});
$dialog.dialog('open');
};
</script>
that close event is inside of a jquery Modal dialog call btw, so the syntax is technically correct
You could persist the values wherever you want in the DOM but if you want to send them to the server you have a couple of options:
Form with hidden fields (you said you don't want this)
AJAX request that will harvest the values from the DOM
Anchor with the values in the query string
Or simply persist the values on the server. I guess that you are using some data store there which could be used.
UPDATE:
Now that you have shown your code it is clear why it is not working. You do not have any hidden fields (browse at the HTML source code in your browser to see that they are missing). You have just called the Html.Hidden helper on the server but you never outputted the result to the HTML
Now add your hidden fields correctly:
#Html.Hidden("popId", TempData["POPULATIONID"], new { id = "hidPopID" })
#Html.Hidden("popId", TempData["POPNAME"], new { id = "hidpnID" })
#Html.Hidden("popId", TempData["ROWNUM"], new { id = "hidrownumID" })