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'
})
Related
My layout.cshtml contains:
<li>User</li>
<div ng-view></div>
This is my controller:
and its action methods:
public class UserController : Controller
{
// GET: Admin/Default
BMS2Entities _db = new BMS2Entities();
public ActionResult Index()
{
var emp = _db.AspNetUsers.ToList();
return Json(emp, JsonRequestBehavior.AllowGet);
}
And index.cshtml and index.js file inside:
index.js contains server call to usercontroller inside admin area:
app.controller('userController', function ($scope, $http) {
$http({ method: 'Get', url: 'Areas/Admin/User/Index' })
.then(function (response) {
$scope.depts = response.data;
});
});
and finally myapp.js file for routing:
var app = angular.module('myAppS', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/User', {
templateUrl: 'Areas/Admin/Views/User/Index.cshtml',
controller: 'userController'
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
but the codes are not working and it does not display cshtml and shows
https://localhost:44382/Common/Home#/User in the browser.
$routeProvider.when('/User', {
templateUrl: 'Areas/Admin/Views/User/Index.cshtml',
controller: 'userController'
});
You need to prefix root path in templateUrl and same thing in while calling controller's action.
Did you write ng-app directive in layout.cshtml?
And I think the syntax for tag should be like
User
Hope this Helps!
I am using ngUpgrade and I dont know how to handle the routing between ng2 and ng1. If I am in ng2 component, how do I route to ng1 controller? and viceversa.
I am using ui-router for the ng1. For ng2 I am using the router on the angular team.
Thanks all!
First you need to have defined your routes as normal in both Angular 1.x and 2.x apps.
app.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
And in the Angular 2 Module:
Module.config(($routeProvider) => {
$routeProvider
.when('/user/:id', {template : '<user-details></userdetails>'})
.when('/users', {template : '<user-list></userlist>'});
});
You can create a class called Ng1Ng2UrlHandlingStrategy and in there devide your routes between them:
class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy {
shouldProcessUrl(url) { return url.toString().startsWith("/home") || url.toString().startsWith("/aboute") || url.toString().startsWith("/contact"); }
extract(url) { return url; }
merge(url, whole) { return url; }
}
And in your main component:
providers: [
// Providing a custom url handling strategy to tell the Angular 2 router
// which routes it is responsible for.
{ provide: UrlHandlingStrategy, useClass: Ng1Ng2UrlHandlingStrategy }
]
Finally, update the root component to include an Angular 2 router outlet.
#Component({
selector: 'root-cmp',
template: `
<router-outlet></router-outlet>
<div class="ng-view"></div>
`,
})
export class RootCmp {}
I have an Angular MVC app that has couple of controllers. Default and another custom controller that I added.
http://example.com/home/
http://example.com/ManageSummaryInfo/
All my business logic lies with ManageSummaryInfo Controller.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ManageSummaryInfo", action = "HomePage", id = UrlParameter.Optional }
);
In Angular Routing, I have it like this,
$routeProvider.when('/showsummary',
{
templateUrl: 'ManageSummaryInfo/ShowSummary',
controller: 'ShowSummaryController'
});
$routeProvider.when('/showerror',
{
templateUrl: 'ManageSummaryInfo/ShowError',
controller: 'ShowErrorController'
});
$routeProvider.when('/showplatform',
{
templateUrl: 'ManageSummaryInfo/ShowPlatform',
controller: 'ShowPlatformController'
});
My Views are also configured around ManageSummaryInfo Controller, but when I run I get to the home page, after which I click on one of elements should take me to the next page. But, I dont get routed and I got 404 - The resource cannot be found.error.
This is how my views look,
Views
--ManageSummaryInfo
----HomePage.cshtml
----Index.cshtml
----ShowSummary.cshtml
----ShowError.cshtml
----ShowPlatform.cshtml
My question, is when we have controllers in our route (ie, http://example.com/ManageSummaryInfo/- how would Angular route things and why mine getting file not found error.
I'm new to C# MVC Framework. Am I missing something related to ASP.NEt Routing ?Any help would be appreciated. I have tried to be eloborate, but if you would need more info, I'm happy to provide more code(Pastebin or something.
Thanks in advance!
Edit:
Adding Controller Class as per request,
public class ManageSummaryInfoController : Controller
{
// GET: ManageSummaryInfo
public ActionResult Index()
{
return View();
}
public ActionResult HomePage()
{
return View();
}
public ActionResult ShowPlatform()
{
return PartialView("ShowPlatform");
}
public ActionResult ShowSummary()
{
return PartialView("ShowSummary");
}
public ActionResult ShowError()
{
return PartialView("ShowError");
}
}
1)In the view(html code) on the link(a element) with the href showsummary (and the other also) add '#' before 'showsummary'.
2)Check you have
<script src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.min.js></script>
3)Check you have dependecy to ng-route :
angular.module('myModule', ['ngRoute']);
Angular routing work on html file only(not on chtml),so create html file instead.
var adminApp = angular.module('adminApp', ['ngRoute']);
adminApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/ar', {
templateUrl: 'auto_responder.html',
controller: 'arCtrl'
}).
when('/broadcast', {
templateUrl: 'broadcast.html',
controller: 'broadcastCtrl'
}).
otherwise({
redirectTo: '/ar'
});
}]);
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 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