Spring Boot ngRoute - angularjs

I'm trying to make a single page application with a Spring back end and an AngularJS front end. I've followed tutorials and looked up similar questions but ngRoute just doesn't seem to work with a Spring back end (I got it to work with a NodeJS back end).
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Spring Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="../static/index.js"></script>
</head>
<body ng-app="index" ng-controller="indexController">
test
<div ng-view=""></div>
</body>
</html>
test.html
<div>
Template loaded
</div>
index.js
'use strict';
const indexModule = angular.module('index', ['ngRoute']);
indexModule.controller("indexController", function indexController($scope) {
});
indexModule.config(function($routeProvider) {
$routeProvider.when('/test', {templateUrl: 'test.html'});
});
SringDemoController.java
package com.springdemo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SpringDemoController {
#RequestMapping({ "/" })
public String getIndexTemplate() {
return "index";
}
}
I get this error when I click the link and the URL changes to http://localhost:8080/test

Here is the solution.
The Index page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test title</title>
</head>
<body ng-app="TestApp">
<div>
<h1>The Index</h1>
<ul>
<li>
<a ng-href="#!/test"> Temp One</a>
</li>
</ul>
<div ng-view=""></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.js"></script>
<script src="js/config.js"></script>
<script src="js/controller/main.js"></script>
<script src="js/controller/test.js"></script>
</body>
</html>
The Router config (its called config.js)
'use strict'
angular.module('TestApp' , ["ngRoute"])
.config(function($routeProvider){
$routeProvider
.when('/' , {
templateUrl : "view/main.html",
controller : 'MainController',
controllerAs : 'main'
})
.when('/test' , {
templateUrl : "view/test.html",
controller : 'TestController',
controllerAs : 'test'
})
.otherwise({
redirectTo: '/'
});
});
And the server-side controller for the route :
package com.testApp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class ServerController {
#RequestMapping(value = "/test")
public String getTestTemp() {
return "static/test";
}
}
UPDATE :
actually, the method inside the ServerController is not needed. It can be written as follows
package com.testApp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping(value = "/test")
public class ServerController {
}
So if you write any REST method in this controller, the endpoint from both client and server side will be /test/{the Name of your endPoint }
Here is the Project Structure
If you add more templates, make sure you create the routeon the client side and also the server side

Related

controller is not working with route functionality

I am new in angularjs tech. I have implemented one registration function in my project.
I have created one js file for routing and controller functionality in my project and its working fine, If i will do separate router and controller file then I am application is failing.
I need to do separate file for the router and controller.
Below is my code in one file.
app.js file
var app = angular.module('crasApp', [ 'ngRoute' ]);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl : "./views/xyz.html",
controller : "searchCtrl"
}).when("/registration", {
templateUrl : "./views/abc.html",
controller : "MainCtrl"
}).when("/view", {
templateUrl : "./views/viewsdata.html",
controller : "overViewCtrl"
});
});
app
.controller(
"MainCtrl",
function($scope, $http) {
console.log("Hi");
});
index.html
<!DOCTYPE html>
<html ng-app="crasApp">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<head>
<!-- Use Bootstrap -->
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/abn-stylesheet.css">
<link rel="stylesheet" href="./css/style.css">
<script src="./javascripts/jquery/jquery-1.12.4.js"></script>
<script src="./javascripts/jquery/jquery.min-1.12.4.js"></script>
<script src="./javascripts/angular/bootstrap.min.js"></script>
<!-- <script src="./javascripts/angular/angular.min.js"></script> -->
<script src="./javascripts/controllers/app.js"></script>
<!-- <script src="./javascripts/angular/angular-route.js"></script> -->
<script src="./javascripts/router/router.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
</head>
<div ng-view></div>
</html>
xyz.html
<!DOCTYPE html>
<html ng-app="crasApp">
<head>
<!-- Use Bootstrap -->
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/abn-stylesheet.css">
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/ngDatepicker.css">
<script src="./javascripts/jquery/jquery-1.12.4.js"></script>
<script src="./javascripts/jquery/jquery.min-1.12.4.js"></script>
<script src="./javascripts/angular/bootstrap.min.js"></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> -->
<script src="./javascripts/controllers/app.js"></script>
</head>
<body ng-controller="MainCtrl">
Hi
</body>
<html>
So, Its working file if I am using one app.js file
I want to do seprate router and controller file.
router functionality i moved into different file and its working router functionality but not working controller functionality..
Separate router file as below.
router.js
var app = angular.module('crasApp', [ 'ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl : "./views/retrieveTerminationReason.html",
/*controller : "searchCtrl"*/
}).when("/registration", {
templateUrl : "./views/registration.html",
/*controller : "MainCtrl"*/
}).when("/view", {
templateUrl : "./views/forbearanceRegistartionOverview.html",
/*controller : "overViewCtrl"*/
});
});
app.js as a controller
var app = angular.module('crasApp', []);
app
.controller(
'MainCtrl',
function($scope, $http) {
console.log("Hi");
});
Please any one can help on this part.
In router.js, change var app = angular.module('crasApp', [ 'ngRoute']) to var app = angular.module('crasApp').
Also, in app.js, your declaration should be: var app = angular.module('crasApp', ['ngRoute']);. Since you have a single module, 'crasApp', you must declare it's dependencies when you declare the module itself.
What you have currently is re-creating the module vs. appending functionality.
Also, be sure to include your router.js as well in your HTML .
the issue
when you're using var app = angular.module('crasApp', [ 'ngRoute']); in your route.js file you are initializing new module NOT adding config to existing module!
the best approach for structuring an Angular App is NOT using variable you can call your module in a different way like:
app.js
var MODULE_NAME = 'crasApp'
angular.module(MODULE_NAME, ['ngRoute']);
to create controller controllers.js
angular.module(MODULE_NAME).controller('MainCtrl',function($scope, $http) { //Note removing the dependencies array
console.log("Hi");
});
to create config routes.js
angular.module(MODULE_NAME).config(function($routeProvider) { //Note removing the dependencies array
$routeProvider.when("/", {
templateUrl : "./views/retrieveTerminationReason.html",
/*controller : "searchCtrl"*/
})
in your index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/routes.js"></script>
<script src="js/controllers.js"></script>
</head>
Note you don't need ng-controller directive in your HTML because defining it in routes is enough
separating services
create services.js for example
angular.module(MODULE_NAME).factory('Users',function($http,$q) {
return {
getUsers:function(){
var def = $q.defer();
$http({url:'URL_HERE',method:'GET'}).then(function(res){
def.resolve(res)
},function(err){
def.reject(err);
})
}
}
})
using in controller
angular.module(MODULE_NAME).controller('MainCtrl',function($scope, Users) { //Note Users is the name of the factory created above
Users.getUsers().then(function(res){
$scope.users=res;
},function(err){
$scope.error = err;
})
});

AngularJS: Load resources from one project into another

I have two Spring Boot projects, Project1 and Project2. I have angular code in both the projects under 'static' folder. I am trying to route to the resources in Project2 from Project1 as below,
src/main/resources/static/index.html (in Project1)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="app.js">
</script>
</head>
<body>
<a ui-sref="spendCar">Click here to go to Spend Cat of Project2</a>
</body>
</html>
src/main/resources/static/app.js (in Project1)
var proj1 = angular.module('proj1', ['ui.router']);
proj1.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'partial-home.html'
})
.state('spendcat', {
url: '/spendcat',
templateUrl : 'http://localhost:8090/spendcat' //calling Project2's end point
});
});
In Project2 I have a controller as below,
#Controller
#RequestMapping("/spendcat")
#CrossOrigin
public class SpendCatController {
#RequestMapping(value = "", method = RequestMethod.GET)
public String getSpendCatPage() {
return "spendcatpage"; //spendcatpage.html is under 'static' folder.
}
}
src/main/resources/static/spendcatpage.html (in Project2)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="sc.js">
</script>
</head>
<body>
<div>Welcome to spend category page</div>
<input type="button" onclick="doClick()" value="Click Here">
</body>
</html>
I get error when "Click Here" button is clicked. If the javascript function doClick() is directly included in html file, then it works. Please suggest me how to load all resources of project2 in project1.

Angular simple routing is not working

I'm tring build single page app, but i have problem with angular routing it doesnt work.
I'm using spring boot, thymeleaf and angular 1.4.8.
I'm basing on this example https://code.angularjs.org/1.4.8/docs/api/ngRoute/directive/ngView
Here is my main controller:
#Controller
public class HomeController {
#RequestMapping(value = "/")
public String index(){
return "index";
}
}
Here is my index.html
<!DOCTYPE html>
<html>
<head ng-app="ngViewExample">
<title></title>
</head>
<body>
<div ng-controller="MainCtrl as main">
test
<div ng-view=""></div>
</div>
<script type="text/javascript" th:src="#{/js/lib/angular.js}" />
<script type="text/javascript" th:src="#{/js/lib/angular-route.js}" />
<script type="text/javascript" th:src="#{/js/lib/angular-resource.js}" />
<script type="text/javascript" th:src="#{/js/lib/underscore.js}" />
<script type="text/javascript" th:src="#{/js/lib/restangular.js}" />
<script type="text/javascript" th:src="#{/js/src/index.js}" />
</body>
</html>
index.js
var home = angular.module('ngViewExample', ['ngRoute']);
home.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: 'test.html',
controller: 'TestCtrl',
controllerAs: 'test'
})
}])
.controller('MainCtrl',
function() {
})
.controller('TestCtrl',
function() {
});
And content I wish to pass to ng-view
test.html
<div>
Hello
</div>
Everything is loading fine but routing just not working here.
you linked me this question yesterday:
here my answer so far
Let's start with How to provide static content via Spring Boot
As shown in this spring blog all resources placed in the directories
/META-INF/resources/
/resources/
/static/
/public/
inside your classpath are added as static resources. So for example just put your index.html into the /public/ directory inside your classpath and you won't need your HomeControlleranymore
Now to the angular part
First of all put the ng-app directive at the <html>or the <body> tag.
I can't see any problems with your angular code so far. Can you verify, that the partial HTML is available at the /test endpoint? If not please follow the steps i told you above. Just put the test.html inside the /public/directory inside your classpath.
Are there any errors in the console if you open the browser devtools and reload the page?
If you could provide your project on Github i will have a look at it.
First of all, Please ng-app directive placement <body> or <html> tag
<body ng-app="ngViewExample">
Template url
templateUrl: 'test'
MvcConfig.java
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("test");
}
}
SpringBootApp
#SpringBootApplication
#ComponentScan(basePackages = {"com.example.spring"})
public class SpringAngularApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAngularApplication.class, args);
}
}
where do you put test.html. It should be in /resources/static folder. If in /resources/templates it will be process by thymeleaf and need to be added in ViewControllerRegistry
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("test");
}
}

How to use ng-view in jsp pages for spring

Trying to implement a user authentication with simple http session using angular and spring.
In index.jsp(my home page), a ng-view is being used.
But since the $routeProvider is not able to find the template from templateUrl for url /login(which i think is the reason for the errors), hence only index.jsp page is getting rendered, and ng-view is not rendering and errors are also occuring.
Error and relevant codes are attached below along with a snapshot of my folder structure.
According to my limited knowledge, it is the way i am referring to my templates through templateUrl that is causing the error
error snippet
Error: [$injector:unpr] Unknown provider: $templateRequestProvider <- $templateRequest <- $route <- ngViewDirective
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="PMApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AUTH</title>
<script data-require="angular.js#*" data-semver="1.2.13"
src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-route.js"> </script>
<script type="text/javascript" src="<c:url value="/resources/js/app.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/LoginController.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/MainController.js" />"></script>
</head>
<body>
<h2>Hello World!Just trying the AUTHENTICATION . . .</h2>
<div ng-view></div>
</body>
</html>
app.js
var PMApp = {};
var App = angular.module('PMApp', ['ngRoute']);
App.config(['$routeProvider', function($routeProvider) {
console.log("in routeprovider");
$routeProvider.when('/login', {
templateUrl: '/resources/views/loginLayout.html',
controller: LoginController
});
$routeProvider.when('/main', {
templateUrl: 'resources/views/mainLayout.html',
controller: MainController
});
$routeProvider.otherwise({redirectTo: '/login'});
}]);
App.run(function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log("Routechanged sessionId="+$rootScope.SessionId);
if ($rootScope.SessionId == '' || $rootScope.SessionId == null) {
// no logged user, we should be going to #login
if (next.templateUrl == "resources/views/loginLayout.html") {
// already going to #login, no redirect needed
} else {
// not going to #login, we should redirect now
$location.path("/login");
}
}
});
});
Do ask for more details if required.
Thanks in advance.
It was the version that was creating the problem. update it to 1.3.1 and everything works like a gem......

angular routes, not getting a # after index.html

I am trying to set up a SPA with angular, and with the current code it is not working, while run on a server. My index.html does not have a # after it, which I think it should for the SPA. I am curious why I am not getting a # in the url's. for example, navigating to the index i get something like localhost:4000/index.html/ instead of localhost:4000/index.html#/. When i try to navigate to localhost:4000/index.html/home i get a 404 error. Can anyone tell me why this is so, or if there are any other issues you can spot.
This is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ski</title>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
</head>
<body ng-app="Ski">
<ng-view></ng-view>
<script src="js/app.js"></script>
<script src="js/routes.js"></script>
</body>
</html>
angular routes :
angular.module('Ski').config(function($routeProvider) {
'use strict';
.when('/home', {
templateUrl: 'templates/home.html'
})
.when('/map', {
templateUrl: 'templates/map.html'
})
.otherwise({
redirectTo: '/'
});
});
app.js
angular.module('Ski', ['ngRoute']);
Templates:
this on is templates/maps
<div>
<h1> Hello World </h1>
</div>
this one is templates/home
<h1> Home </h1>

Resources