I'm having trouble working with Angular.js $routeProvider, I have a link on a menu in which will be mapped via the angular route and will later call an action in the Spring, but it does not work! Below are my files...
snippet of menu.jsp
<li>
<a class="tooltip-tip ajax-load" href="#" title="Clientes"><i class="entypo-user"></i><span>Clientes</span></a>
<ul>
<li><a class="tooltip-tip2 ajax-load" href="#/customer" title="Novo Cliente"><i class="entypo-newspaper"></i><span>Novo Cliente</span></a></li>
</ul>
</li>
app.js
var app = angular.module('jooceboxCrm', ['ngRoute', 'service', 'customer', 'ui.bootstrap']);
customer.js
var app = angular.module('customer', []);
app.config(function($routeProvider, $locationProvider, $httpProvider) {
//Set CSFR Token
$httpProvider.defaults.headers.common["X-CSRF-TOKEN"] = $("meta[name='_csrf']").attr("content");
console.log('Acesso a ConfiguraĆ§Ć£o do RouteProvider.');
$routeProvider.when('/customer', {
templateUrl : '/viatge/auth/customer',
controller : 'customerController'
}).otherwise({
redirectTo : '/customer'
});
});
app.run([ '$rootScope', function($rootScope) {
$rootScope.customer = [];
console.log('app.run');
} ]);
app.controller([ 'customerController', function($scope) {
console.log('customerController');
} ]);
EDIT
I'am using Spring MVC and Tiles framework for rendering my pages. So my value for template url points to a method in Spring MVC controller:
templateUrl : '/viatge/auth/customer'
#Controller
#Transactional(propagation = Propagation.REQUIRED)
#RequestMapping("/auth")
public class CustomerController {
final static Logger logger = LoggerFactory
.getLogger(CustomerController.class);
#Autowired
private CustomerFacade customerFacade;
#RequestMapping("customer")
public String customerScreen() {
return "customer/newCustomer";
}
}
I'm following this tutorial
Related
I have used Spring Boot and Angular JS application. My home page is getting viewed from my controller but routing to new page using angular is not happening,
Angular JS - code
use strict
var demoApp = angular.module('app', [ 'ngRoute']);
//configure our routes
demoApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'home.html',
controller: 'mainController'
})
// route for the about page
.when('/about', {
templateUrl: 'views/about.html',
controller: 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl: 'contact.html',
controller: 'contactController'
});
});
// create the controller and inject Angular's $scope
demoApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.HomeMessage = 'Home Controller Called !!!';
});
demoApp.controller('aboutController', function($scope) {
$scope.AboutMessage = 'About Controller Called !!!';
});
demoApp.controller('contactController', function($scope) {
$scope.ContactMessage = 'Contact Controller Called !!!';
});
Spring Boot Code
#RequestMapping("/main")
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "home";
}
}
I am getting my home page but from my html I am traversing to about and contact page where routing is not happening
HTML Code
<ul class="nav navbar-nav navbar-right ">
<li><i class="fa fa-home"></i>Home</li>
<li><i class="fa fa-shield"></i>About</li>
<li><i class="fa fa-comment"></i>Contact
</li>
</ul>
This is the home page it is displaying http://localhost:8080/main/#!/ and if I try to traverse to contact or about it is displaying the same page and it is appending "!" mark
http://localhost:8080/main/#!/#about. Can anyone suggest how is it possible to traverse to new page
Got this below error in console
Error: [$compile:tpload] Failed to load template:
home.html (HTTP status: 404 )
http://errors.angularjs.org/1.6.9/$compile/tpload?p0=home.html&p1=404&p2=
at angular.js:116
I am new to Spring framework and Angular JS. I am developing Html files with angular js as fronted and Spring mvc as backend. Please find the dispatcher-servlet configuration as below.
<context:component-scan base-package="com.hourforyou" />
<mvc:resources mapping="/assets/**" location="/assets/" />
<mvc:resources mapping="/pages/**" location="/WEB-INF/pages/" />
<mvc:annotation-driven />
First request arrives to Indexcontroller and properly renders the view.
#Controller
public class IndexController {
#RequestMapping("/")
public String login() {
return "pages/login.html";
}
}
After validating user in login.html, i am redirecting to home.html. But its not working.
#Controller
#RequestMapping(URL.HOME)
public class HomeController {
#RequestMapping
public String getHome() {
return "pages/home.html";
}
My app.js code
'use strict';
var App = angular.module('backoffice', [ 'ngRoute' ]);
App.config(function($routeProvider) {
$routeProvider.when('/home', {
templateUrl : 'home.html',
controller : 'HomeController'
}).when('/dashboard', {
templateUrl : 'dashboard.html',
controller : 'DashboardController'
}).otherwise({
redirectTo : '/'
});
});
Request comes to getHome(), but its not redirecting to home.html file. Please any one tell me what i am doing wrong.
You can write like this...
Instead of routing in your server side just return a success/fail/invalidstring to your api request.
Based on which you can route to respective page after validation in angular side.
In Spring controller
#RequestMapping(value = { "/login" }, method = RequestMethod.POST)
#ResponseBody
public String checkLogin(#RequestBody User user) {
String status = service.login(user);
return status;// return success or fail or invalid based on your logic in serviceImpl class
}
In app.js
.state('home', {
url:'/home',
templateUrl: 'path/to/Home.html',
controller:'Home'
})
In login controller
scope.login = function(user){
Repository.login(user)
.then(function (response){
if(response.data.status = "success")
{
state.go("home");
}
else
{
alert(" Password is Invalid...");
state.go("login");
}
});
};
}
Thanks for answering. This is what i exactly done in my code. But the solution is i created an index.html file , mentioned ngview directive in a div inside body tag. First Call to spring dispatcher will return index.html.
#Controller
public class IndexController {
#RequestMapping("/")
public String login() {
return "pages/index.html";
}
in index.html
<html ng-app='backoffice' ng-cloak>
<head>
<base href="/module-backoffice/">
<head>
//js files
</head>
<body>
<div ng-view></div>
</body
in App.js routing
when('/', {
templateUrl : 'pages/login.html',
controller : 'LoginController'
})
After sucessful login routing
.when('/home.html', {
templateUrl : 'pages/home.html',
controller : 'HomeController'
})
Hello I m creating an angularJs SPA project with asp.net mvc. I want to implement angular routing in m project so I m trying to change the routes via angular routing. this is my code.
Angular routes.
var app = angular.module('myApp', [
'ngRoute',
'myApp.ctrl.testCtrl'
])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/test', { templateUrl: '/home/test', controller: 'testCtrl'})
}]);
My controller
var app = angular.module('myApp.ctrl.testCtrl', [])
.controller('testCtrl', ['$scope', function () {
console.log('in Controller');
}])
RouteConfig.cs
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Now When I write
TestPage
also tried
TestPage
but none of these works.
The Url changes to
http://localhost:57026/#!#%2Ftest
so the routing does not work. Please point me out where i m going wrong
You should write an ng-click event on anchor tag
TestPage
And in click function use in controller
$scope.clickFunction = function(){
$location.path("/test");
}
I'm new to angularjs and i'm making a website using ASP.NET MVC and AngularJs.I used angularjs ui router for route from one page to another.
With ui-sref tag every thing is ok but when user refreshes the browser page or enter url it fails to match to a state.
The question is how to set states and what actions needed in my controllers.
here are my codes.if any other code is required tell me.
my controller
public ActionResult Index()
{
return View();
}
public ActionResult NewsListPage()
{
return Redirect("#NewsListPage");
}
public ActionResult NewsDetailPage(int? newsId)
{
return Redirect("#NewsDetailPage");
}
my main angular file including module creation and config
var app = angular.module('abtinApp', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('A',
{
url: '/News/NewsListPage',
templateUrl: '/Angular/NewsListPage'
})
.state('B',
{
url: '/News/NewsDetailPage/:newsId',
templateUrl: '/Angular/NewsDetailPage'
})
.state('C',
{
url: '^/News/NewsDetailPage/:newsId',
templateUrl: '/Angular/NewsDetailPage'
});
$urlRouterProvider.otherwise('/News/NewsListPage');
$locationProvider.html5Mode({ enabled: true, requireBase: false });
}
]);
my index.cshtml
...
<div ng-app="abtinApp">
<a ui-sref=".A">Main</a>
<a ui-sref=".B">Detail</a>
<div ui-view></div>
</div>
...
angular controller
public ActionResult NewsDetailPage()
{
return View();
}
public ActionResult NewsListPage()
{
return View();
}
and NewsDetailPage.cshtml
<div ng-controller="NewsDetailController">
<h3>Details</h3>
<h3>{{newsId}}</h3>
</div>
and NewsListPage.cshtml
<h3>News</h3>
<div ng-controller="NewsController">
<div ng-repeat="newsItem in newsToShow">
<h3>
<a ui-sref="B({newsId: '{{newsItem.Id}}'})"> {{newsItem.Title}}</a>
</h3>
<p>
{{newsItem.NewsSummary}}
</p>
</div>
</div>
there is nothing especial in my angular controllers.
thank you.
After searching a lot and wasting some time,i found out by removing
$locationProvider.html5Mode({ enabled: true, requireBase: false });
every thing is fine but the new problem will be the ugly urls that is not important to me.
still any other answer will be appreciated.
I'm a beginner to AngularJS and have the following question. I'm playing with ngRoute module and this is my code so far:
html:
<nav ng-controller="navController as nav">
<ul>
<li ng-repeat="item in navItems">
{{ item.name }}
</li>
</ul>
</nav>
<div id="main">
<div ng-view></div>
</div>
app.js
(function(window) {
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
if (window.history && window.history.pushState) {
$locationProvider.html5Mode(true);
}
}]);
app.controller('mainController', ['$scope', function($scope) {
$scope.message = 'Hello from home page';
}]);
app.controller('contactController', ['$scope', function($scope) {
$scope.message = 'Hello from contact page';
}]);
app.controller('navController', ['$scope', function($scope) {
$scope.navItems = [
{ name: 'Home', url: '/' },
{ name: 'Contact', url: '/contact' }
];
}]);
})(window);
And it works fine. Angular renders menu, and when I click on the link it shows me desired page. But except in the following case. When it displays the homepage (url: http://localhost:3000) and i manually add to the url address "/contact" then I'm getting blank page with error "Cannot GET /contact". Could someone explain me why this is happening and how can I fix it? I would appreciate any help. Thanks.
In fact you need the # (hashtag) for non HTML5 browsers.
Otherwise they will just do an HTTP call to the server at the mentioned href. The # is an old browser shortcircuit which doesn't fire the request, which allows many js frameworks to build their own clientside rerouting on top of that.
You can use $locationProvider.html5Mode(true) to tell angular to use HTML5 strategy if available.
Here the list of browser that support HTML5 strategy: http://caniuse.com/#feat=history
Source: AngularJS routing without the hash '#'