GAE and Angular: How to update data of a HTML JINJA template - javascript

I have a problem with GAE and Angular about updating data dynamically on an HTML template.
What I want is when a new user is inserted into the system it must automatically be shown on the page which lists all the user of the system.
I don't know how to that. I read about Angular and it seems a good framework to update data dynamically on an HTML web page.
I get the page using JINJA and filling the template by querying the NDB datastore where all the Users are stored.
That's the code of the webapp handler which "handles the page":
class TestA(BaseHandler):
def get(self):
template = JINJA_ENVIRONMENT.get_template('templates/Ang2.html')
Users=datastore._retrieve_all_user()
w = self.response.write
w(template.render({'Users': Users}))
When I insert a new user the page with all the Users is shown, meanwhile in another tab the updates aren't shown, but if I refresh the page manually the new user is shown.
So, what I want is obtaining the same result but in automatic way.
The point is I want to refresh periodically the HTML page, in order to show the eventual new users.
So I focused on Angular, and particularly on $interval and $route.reload(), but I have tried to make something which works, but i haven't got anything.
That's the code of the template:
<!doctype html>
<html ng-app="demoApp">
<head>
<title>Hello from a template page!</title>
<link rel="stylesheet" type="text/css" href="/css/helloworld.css">
</head>
<body>
<h1>Hello world HTML template.</h1>
<div data-ng-controller="MyController">
<h3>Elenco utenti:</h3>
<ul>
{% for User in Users %}
<li><b>{{User.username}}</b>: {{User.email}} </li>
{% endfor %}
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var demoApp = angular.module("demoApp", []);
myapp.controller("MyController", function($scope, $interval){
$interval(callAtInterval, 5000);
});
function callAtInterval($route) {
$route.reload();
}
</script>
</body>
Any tips how to do that?
PS: I know the solution isn't elegant, but I chose this solution because I need to know how to do that because it will be useful for next steps of the developing of features of my webapp

Don't refresh the page to update data. Angular was meant to update data without refresh.
Create an API as interface for Datastore operations. Use Angular to execute Promise requests on this API, changing the scope depending on the promise return.
Read the documentation on how angular works first, then learn how to create APIs.
Angular
https://docs.angularjs.org/guide/concepts
API assuming you are using Python
https://www.codementor.io/sagaragarwal94/building-a-basic-restful-api-in-python-58k02xsiq

Related

Get the contents of a div element from one site to another

I have an argument in JS which holds pretty much the data. It's the server information to my server. It changes often, e.g 20/64 or 32/64. You get the point.
I am trying to get the contents of the data to go on an external site, however, when I try, it doesn't work.
To summerise, I have a div which holds the data, I want to get that data using JS and put it on an external site which isn't using the same domain or web server.
HTML FILE:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<div id="serverstats-wrapper"></div>
<script src="import.js"></script>
</body>
JS File:
$(document).ready(function(){
$.post("query.php", {},
function (data) {
$('#serverstats-wrapper').html (data);
});
});
var the_main = document.getElementById("serverstats-wrapper");
var the_data = the_main.textContent ? the_main.textContent : the_main.innerText;
I want to get the text from the html file to the js file then take it to an external website.
Tasid! This won't work! JS does't have such a technique implementet. To do so, you need node.js. This allows you to send the data over a socket to your other webserver.
It does't work difrently, because JS is executed direct on your PC.
You can grab data from another site; but you cannot inject JS code into another site. Here are some methods to retrieve html from another site: Include another HTML file in a HTML file

Access Angular variable within script tag

I am making a web app:front-end in Angular and backend in Rails.
I am using LinkedIn's member profile plugin which shows person's profile based on URL being passed. Here is the code for this plugin.
<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/MemberProfile" data-id="(Your LinkedIn URL)" data-format="inline" data-related="false"></script>
I want to make data-id part dynamic. Basically, I will let my users to write their linkedin address in text box and save it to Angular's variable. When the value changes, I want that value gets assigned to data-id. But I'm not sure whether data-id can access a variable in Angular.
Quite simple. Create your app along with a global controller that will be initialised on your html tag like so:
<html ng-app="app" ng-controller="myctrl">
<head>
<script type="IN/MemberProfile" data-id="{{myId}}" data-format="inline" data-related="false"></script>
</head>
</html>
And have this as your controller and app initialisation, or something similar:
var app = angular.module('app', []);
app.controller('myctrl', ['$scope', function($scope){
$scope.myId = 123;
}]);
To break it down, $scope.myId will be assigned the LinkedIn ID, and it is output on the page inside the head tag (I'm guessing that's where you want it) within the data-id attribute on the script tag.
WORKING EXAMPLE

AngularJS - importing controllers inside controllers

I have diferents controllers in my webpage, each controller is in a different .php document. Each .php document represents a diferent part of the webpage. (It's similar to spotify).
player.php: (Where the user can play some music with an audio player)
<html ng-app="decibels-interactive" lang="en">
<body ng-controller="InteractiveController as interactCtrl">
panel_admin.php: (where the user can modify its data and some data of the webpage)
<html lang="en" ng-app="decibels-admin">
<body ng-controller="AdminController as AdminCtrl" ng-init="AdminCtrl.sessionCtrl()">
player.php and panel_admin.php have its respective player.js and panel_admin.js with its .controllers running correctly.
player.js:
var decibelsInteractive = angular.module("decibels-interactive", []);
decibelsInteractive.controller('InteractiveController', function ($scope, $log) {
panel_admin.js:
var adminControl = angular.module("decibels-admin", []);
adminControl.controller("AdminController", function($scope){
Now, I have the menu bar in menu.php, where I use in player.php document, imported with:
//player.php
<html ng-app="decibels-interactive" lang="en">
<body ng-controller="InteractiveController as interactCtrl">
<?php include('includes/menu.php'); ?>
//here some html code
</body>
</html>
menu.php: (menu is a menu bar where the user have some options, and it also have its username and logout option)
<div class="navbar-fixed" ng-controller="InteractiveController as menu2">
//some html code
</div>
menu.js:
app.controller('menu2', function($scope) {
$scope.content = '';
});
The problem that I have is that as you can see, I import the document menu.php inside player.php.
I also want to import the menu.php inside panel_admin.php and be able to use some methods that I have in menu.js, so the code that I have in menu.php (ng-controller="") is not correct (or I think so). -Because when I use it in panel_admin.php it will be in conflict with ng-controller name.
Someone told me that I should use services, or that I should define menu in separate module and use it as dependency where I want.
I am new with angularJS so now I'm a little lost. I've been searching information about services and dependencies without success.
I hope to solve this problem and being able to continue programming!
Thank you!

Getting data from Spring MVC in Angular JS in the initial view call

I am new to Angular JS, I have created a Spring MVC web application with Angular JS, I know that from view we can call REST services from Angular JS using resource, restangular, http , But say in Spring form the Controller a view is been triggered and for loading the datas through angular within the view again a REST call from angular is been called from view to the server and gets the datas thereafter for loading, Instead is there any way to pass the json object while triggering the view from Spring controller to the Angular JS at the first time itself.
I have done a similar thing, its working fine but don't know whether its a good approach or not.
Spring controller
#RequestMapping("/getemployee")
public ModelAndView helloWord(){
JSONArray employeeJsonArray = // contains all the information of the employee
return new ModelAndView("employee", "employee",employeeJsonArray);
}
employee.jsp
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 3.0 MVC Series: Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
$scope.employee = [];
$scope.loadData = function(employee)
{
$scope.employee = JSON.parse(employee);
};
});
</script>
</head>
<body ng-controller="MyCtrl">
{{loadData('${employee}')}}
<input type="text" ng-value="employee[0].name"/>
</body>
</html>
Angular really shines when you use it in a "single" page application, so I would suggest using it as you suggested in your "existing approach" as it moves you closer to a single page app design, however, if you are just trying to get some of the features of Angular in an existing request/response application, then you could send your html payload with the data in ng-init as this page demonstrates. It's a RoR example, but I think the point is clear. I think it is a bit of hack, but should get the job done.
<body ng-init="angularVariable = ${variableFromServer}">
html/angular ...
</body>
I recently switched to using angular, the beauty of it is you can ditch jsp's entirely and just have static html as the frontend. Served as a static resource by spring.
To initially populate your form/tables/whatever - lots of different options do it in javascript/angular. But its nice to keep your view seperate from your controllers (ie don't use jsp's).
You can use below code for get user logging,
<input type="text" ng-model ="currentLoging" ng-init= "currentLoging='${pageContext.request.userPrincipal.name}'" />

Javascript single page architecture with module autonomy

I just started this HTML5 project where we decided to make it a single page architecture by leveraging jQuery $.load() method. Unfortunately, as soon as the JS started to grow, we quickly started running into issues where the modules loaded into the master dashboard have no knowledge of their parent.
The architecture looks like this:
dashboard.html (master file)
moduleA.html
moduleA.js
moduleB.html
moduleB.js
moduleC.html
moduleC.js
Since we decided to also keep the JS as separate files, we are having to load all JS files through dashboard.html in order to invoke them individually when modulex is loaded.
So when loading moduleA.html into the dashboard we have to call its corresponding JS. To do this we simply wrote the JS using a Module Pattern so we can easily invoke it by doing a function call, like:
<script>
moduleA
</script>
or this if we want to access a specific property of this member.
<script>
moduleA.someMethod();
</script>
Now, I know there are is gotta be a nicer way of doing this, right? I hate having to have script tags in the HTML modules in order to load its corresponding JS file.
Another limitation of this is the fact that we no longer can work on modules individually, since the scripts and CSS invocation happens on the parent (dashboard.html) so certainly when moduleA.html is loaded directly, it is pure HTML with no script or CSS.
I looked through the other questions but I didn't see anyone with the same problem.
I looked at AngularJS, EmberJS, KO.JS and BoilerPlateJS but none of them addresses what we are trying to accomplish. The only one that has a similar single page concept is jQuery Mobile but I don't know if you can switch from jQuery to jQuery Mobile and everything remains working.
Has anyone face this issue yet? Is there a solution or would I have to go with a custom solution.
Thanks!
I could argue about AngularJS with you. It is exactly what you need
dashboard.html is layout with some directives attached, but power lies in AngularJs if you use ng-view directive
here is example:
dashboard.js
var app = angular.module("modularApp",[]);
app.config(['$routeProvider', "$locationProvider", function routes($routeProvider, $locationProvider) {
$routeProvider.when('/dashboard', {
controller:'HomeCtrl',
templateUrl:'templates/home.html'
});
$routeProvider.when('/moduleA', {
controller:'ModuleACtrl',
templateUrl:'templates/moduleA.html'
});
$routeProvider.when('/moduleB', {
controller:'ModuleBCtrl',
templateUrl:'templates/moduleB.html'
});
$routeProvider.otherwise({redirectTo: "/dashboard"});
}]);
templates/dashboard.html
<html ng-app="modularApp">
<head>
<!--.... include angular minified js file and what else you need...-->
<script type="text/javascript" src="dashboard.js"></script>
<script type="text/javascript" src="moduleACtrl.js"></script>
<script type="text/javascript" src="moduleBCtrl.js"></script>
</head>
<body>
<a ng-href="#/moduleA">Open Module A View</a>
<a ng-href="#/moduleB">Open Module B View</a>
<!-- Add widgets header menus .... -->
<ng-view></ng-view>
</body>
</html>
moduleACtrl.js
var app=angular.module("modularApp");
app.controller("ModuleACtrl",function($scope){
$scope.scopeValue="Hellow from view";
});
moduleBCtrl.js
var app=angular.module("modularApp");
app.controller("ModuleBCtrl",function($scope){
$scope.scopeValue="Hellow from another view";
});
templates/moduleA.html
<div>{{scopeValue}} in module A</div>
templates/moduleB.html
<div>{{scopeValue}} in module B</div>
You can do more complex things with angular then just this. All depends on your needs. Do you have any special requirements :)
Also, you could create your own directive, like ng-view and use your own $route service and $routeProvider so you can add css and javascript you want to dynamically load when some rute match url.
so instead of above routing table, you could have
app.config(['$myRouteProvider', "$locationProvider", function routes($routeProvider, $locationProvider) {
$routeProvider.when('/dashboard', {
javascript:'javascript/dashboard.js',
templateUrl:'templates/dashboard.html',
cssfile: 'css/dashboard.css'
});
$routeProvider.when('/moduleA', {
javascript:'javascript/moduleA.js',
templateUrl:'templates/moduleA.html',
cssfile: 'css/moduleA.css'
});
$routeProvider.when('/moduleB', {
javascript:'javascript/moduleB.js',
templateUrl:'templates/moduleB.html',
cssfile: 'css/moduleB.css'
});
$routeProvider.otherwise({redirectTo: "/dashboard"});
}]);
But that is, pardon on my French, stup. There are couple libs I tried in ruby on rails to acheive similar, but backend is rendering content, or just part of content. But I'm not sure which backend you are using and are you interested to switch to rails anyway.
DomController in BoilerplateJS does what you need, without using any custom HTML attributes. Your dashboard.html can just have place holders where you want to inject your components. I'm just pulling out some html below from BoilerplateJS index.html to show how it works:
<body>
<section id="page-content">
<header>
<section class="theme"></section>
<section class="language"></section>
</header>
<aside>
<section class="main-menu"></section>
</aside>
</section>
</body>
theme, language and main-menu sections above are just place holders in to which relavant components would be injected by the DomController. The DomController can be now used to register the components with appropriate selectors as below:
//scoped DomController that will be effective only on $('#page-content')
var controller = new Boiler.DomController($('#page-content'));
//add routes with DOM node selector queries and relavant components
controller.addRoutes({
".main-menu" : new MainMenuRouteHandler(context),
".language" : new LanguageRouteHandler(context),
".theme" : new ThemeRouteHandler(context)
});
controller.start();
Above code is extracted from "/boilerplatejs/src/modules/baseModule/module.js"

Categories