AngularJs view with Spring : Not showing - angularjs

So I have a simple application AngularJs and Spring mvc. I have a controlller that mapped to the angularJs page and I have this code in a jsp page :
<div ng-app="myApp" ng-controller="myCtrl">
<p>The name is <span ng-bind="person.lastName"></span></p>
{{ lastName }}
</div>
<script src="applications.js"></script>
<script src="controllers.js"></script>
application.js :
var app = angular.module("myApp", []);
controllers.js :
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});
when I run this with Pivotal it dosn't run, but when I access the file directly within my browser it works like a charm, Someone care to explain pls ?
Thank you.
EDIT
WebConfig.java :
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling ( DefaultServletHandlerConfigurer configurer )
{
configurer.enable();
}
}
resources folder :
The URL : http://localhost:8080/gestionprojet/Project/angularjs
My Controller :
#RequestMapping("/angularjs")
public String getAngularJs() {
return "AngularJs";
}

First of all, your files are under /WEB-INF/resources, but you have configured spring to load static resources from /resources. So they can't be served at all. The config should be
registry.addResourceHandler("/resources/**")
.addResourceLocations("/WEB-INF/resources/");
The URL of your page is
/gestionprojet/Project/angularjs
Your page tries to load the script using the relative path
applications.js
So the corresponding absolute path where the browser looks for the JS files is
/gestionprojet/Project/applications.js
which doesn't match with the URLs you choose to serve static resources from. Assuming /gestionprojet is the context path of the application, the absolute URL should be
/gestionprojet/resources/applications.js
So the source code in the JSP should thus be
<script src="${pageContext.request.contextPath}/resources/applications.js"></script>

Related

Spring + AngularJs log in architecture

I build a simple app with an index.jsp (as a welcome page) and after a form-login submission directly to spring controller, i return either index.jsp or homePage.jsp (when user credentials are valid). So angular (routes, components, etc) loads for the first time at homePage.jsp.
I chose this implementation due to the fact that i am allowed to use only one ng-view and i wanted to do this only at my homePage from the time that is my main content.I would like some suggestions without using a 3d party routing such as ui-router.
First submit you from from JSP page to Spring Controller
<form action = "/checkUser">
[Your input tags]
</form>
In Spring
#Controller
public class Login{
#RequestMapping("checkUser")
public String checkUser(#RequestBody Map<String,Object>){
[Check your user is Valid or not]
[If valid]
return "homePage.jsp"
[else]
return "Index.jsp"
}
}
But rather than this i personally prefer Spring Security.
Once you got on your homePage you can load all your necessary js file including the annular js files
And load your views using ng-Route
var app = angular.module('tester',
['ngRoute']).config(function($routeProvider) {
$routeProvider
.when('/tests', {
templateUrl: 'tests.html',
controller: 'TestCtrl'
});
});
app.controller('TestCtrl', ['$scope', function($scope){
$scope.title = "This is a Test Page";
}]);
When You click on Tests link
<div ng-view></div>
Test
tests.html will directly load in ng-view part
For ng-view Plunker

How ng-include builds url in Angular 1.5?

Am using Angular1.5 with asp.net mvc.
By default when my application loads it points to http://domainname/components/Webui/Home/Instructions
Home - controller,
Instructions - Action
public class HomeController : Controller
{
public ActionResult Instructions()
{
return View();
}
}
above url returns an html
which contains below
<div>
<div ng-include src="app/Layout/shell/Shell.html" class="height100">
</div>
</div>
But it is not able to download the shell.html.
it is generating the wrong url as below
http://domainname/components/Webui/Home/app/layout/shell/Shell.html
In the above url why Home is coming ?
My folder structure is
app
layout
shell
Shell.html
Controllers
Views
Home
Index.cshtml
Instructions.cshtm
Please correct me if anything is wrong.
You are using a relative path from index. Append forward slash to path to traverse from project root:
ng-include src="/app/Layout/shell/Shell.html

VisualForce Remoting not working with Separate AngularJS Controller File

I'm facing an issue while working with Visualforce remoting and angularjs. Whenever I'm putting my controller code in separate js Static resource, my code doesn't work. Please help me in figuring out this.
My Visualforce page
<apex:page controller="ApexRemoteActionPageController" docType="html-5.0">
<html>
<body>
<div class="bootstrap" ng-app="ngApp" ng-controller="ContactCtrl" >
<h1 align="center">Click The Button</h1>
<button ng-click="getContacts()" class="btn btn-lg btn-default btn-block">Get Contacts</button>
<p>
<ul>
<li id="{{current.Id}}" ng-repeat="current in contacts" ng-class-even="'rowEven'">{{current.Name}}</li>
</ul>
</p>
</div>
<apex:stylesheet value="//cdn.jsdelivr.net/webjars/bootstrap-sf1/0.1.0-beta.6/css/bootstrap-namespaced.css"/>
<apex:includeScript value="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.11/angular.min.js"/>
<apex:includeScript value="{!$Resource.ContactCtrl}" />
</body>
</html>
</apex:page>
My Controller Static Resource
<script>
var ngApp= angular.module("ngApp", []);
ngApp.controller("ContactCtrl", ["$scope", function($scope)
{
$scope.contacts = [];
$scope.getContacts = function() {
ApexRemoteActionPageController.myContacts(function(result, event) {
$scope.contacts = result;
$scope.$apply();
});
}
}]);
</script>
My Apex Controller
global class ApexRemoteActionPageController {
#RemoteAction
global static List<Contact> myContacts()
{
return [select id, name, email from Contact Order By LastModifiedDate DESC LIMIT 30];
}
}
Whenever I put my controller logic in same Visual Force page it works, but when i move my controller script to separate js Static resource it doesn't.
Your controller static resource is a Javascript file and as such does not need <script> tags. Remove these and I believe your static resource will work as intended.
More detail: If you use <script> tags in your js file, you will end up with markup that nests the script tags and I don't think that will work for you. This is because <includeScript> renders to a script tag in the HTML markup.
I finally found an answer. Yes part of the problem is using <Script> tag in static resource which needs to be removed, but the real problem was not placing namespace prefix before controller when placing a remoting call.
ApexRemoteActionPageController.myContacts(function(result, event)
needs to be
namespaceprefix. ApexRemoteActionPageController.myContacts(function(result, event)
Namespace prefix will not be set by default in Developer Edition, we have to navigate to ....Search bar on leftn hand side in dev account and search for create package ...go to packages and enable Managed package option ...which will give us option to set a namespace prefix for our entire account (classes.controllers...etc) and then come to javascript static resource and put your namespace before controller.methodname and thats it..

Using jquery mobile external page with a angular js controller

Hello im working on a web app project, and we are using jquery mobile for the pages ui and angular for mvc reasons,
Im having a problem using my external pages ( pages that ive load to my index.html), they dont recognize my controllers (only works the controllers that ive put in the index.html)
ill some of my code here to explain my problem
if ive put some angular values in my external page (previews declaration of the controller in my
<div data-role="page" id="ResEjecSuc" class=".paginas"
data-dom-cache="true" ng-controlles="categController" >
)
<span ng-class="sucursal.TIT_CATEGORIZACION">
{{sucursal.TIT_REALIZADA}}</span>
my app only shows: {{sucursal.TIT_REALIZADA}}
my controller init code :
app = angular.module('nevadaProt', [])
app.controller('categController', controlerCateg)
controlerCateg = function($scope, $locale) {
var sucursal = {
TIT_CATEGORIZACION:4,
TIT_REALIZADA:12
}
how ive load and after that transition to my html page:
Load:
$.mobile.pageContainer.pagecontainer("load",
"pages/RappidApps2/ResumenEjecZona.html", {});
transition:
$.mobile.pageContainer.pagecontainer("change", "#ResEjecSuc", {
transition : "pop",
reverse : false
});
how can i make work angular controllers and external jquery mobile pages?
Once you are using Angular, you may create a directive.
app.directive('externalHtml', function(){
return {
restrict : 'E'
,replace : true
,templateUrl : 'pages/RappidApps2/ResumenEjecZona.html'
};
});
then, you html should be something like:
<body>
<div data-role="content">
<external-html/>
</div>
</body>
It always works for me.

Using ng-route with Google-Apps-Script or some means of rendering a partial html view

I am trying to get ng-route working with a google-apps-script web app. I have managed to get basic angular.js functionality working with google-apps-script, but I can't seem to get ng-route to work. I have placed ng-view tags inside a page and have included a separate JavaScript page that contains the routeProvider function.
The ng-view never gets rendered and as far as I can make out the routeProvider does not get called.
Can anyone offer any advice on using ng-route with google-apps-script or suggest another way of rendering a partial html page with google-apps-script
Any answers greatly appreciated.
Have simplified my code and added below:
Code.gs
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
// Build and return HTML in IFRAME sandbox mode.
return template.evaluate()
.setTitle('Web App Window Title')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
index.html
<!-- Use a templated HTML printing scriptlet to import common stylesheet. -->
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<html>
<body ng-app="myApp">
<h1>NG View</h1>
<ng-view></ng-view>
<p>angular check {{'is' + 'working!'}}</p>
<? var url = getScriptUrl();?>
<p id="urlid"><?=url?></p>
</body>
</html>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
Javascript.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-route.js"> </script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider){
console.log('routeProvider config');
var url = document.getElementById("urlid").innerHTML;
console.log('routeProvider config->' +url);
$routeProvider.when("/",
{
templateUrl: url+"?page=_app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
</script>
_app.html
<div>
<h1>{{ app.message }}</h1>
</div>
When this runs angular check {{'is' + 'working!'}} works fine, but the ng-view does not get rendered the java console shows:
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy.
The first obstacle is "sce"
$sce is a service that provides Strict Contextual Escaping services to AngularJS.
Refer link https://docs.angularjs.org/api/ng/service/$sce#trustAsResourceUrl
For the purpose of investigation, I disabled sce (this is not recommended, though)
$sceProvider.enabled(false);
Now the error is shifted to XMLHttpRequest cannot load... No 'Access-Control-Allow-Origin' header is present on the requested resource.
XHR requests to the Google Apps Script server are forbidden
Refer link https://developers.google.com/apps-script/guides/html/restrictions
Google Apps is delivering the files from a different origin than the scripts.google.com and angular js client code is not able to fetch the partial htmls from the same origin.
I guess approach of ng-view is not feasible given the restrictions placed by google apps.
Here is the final modified code
<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider,$sceProvider){
$sceProvider.enabled(false);
console.log('routeProvider config');
var url = document.getElementById("urlid").innerHTML;
console.log('routeProvider config->' +url);
$routeProvider.when("/",
{
templateUrl: url+"?page=_app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
</script>
There has been some time since the question, but I'll post a reply either way.
If your partial html page is not too complicated and big, you can use template instead of templateUrl in the routeProvider, plus create a variable with the html you want to show. Something like this below:
var partial_page = "<span>partial page</span>"
$routeProvider.when("/",
{
template: partial_page,
controller: "AppCtrl",
controllerAs: "app"
}
It worked for me, but I wouldn't advise doing so for a complicated partial page as it may become difficult to read the code

Resources