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.
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'
})
I am having issues with angularJs ui-routing in Mvc app. I have seen several questions regarding this issue. This question in particular seems to be addressing my issue. However I am unable to navigate to different routes.
In my Views/Home/Index.cshtml:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<base href="/">
<h1> Index Page</h1>
<a ui-sref="login">login</a>
<ui-view></ui-view>
In my Angular/app.js:
var myApp = angular.module("myApp", ['ui.router']);
myApp.controller("LoginController", LoginController);
myApp.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('login', {
url: '/Login',
templateUrl: '/home/Login',
controller: LoginController,
controllerAs: 'controller'
})
.state('Index', {
url: '/',
templateUrl: '/home/index'
})
// Handle request for non-existent route
//$urlRouterProvider.otherwise('/home');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
In Login.cshtml:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p> Login Page</p>
<a ui-sref="Index">Index</a>
Route.config
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
In my views/shared/_layout.cshtml:
<body ng-app="myApp">
Possibly related question:
how does $locationProvider.html5Mode(true) and $locationProvider.hashPrefix('!').html5Mode(true) fit in the picture ?
You are using href to navigate yourself to the login state, which is wrong. You should use the ui-sref directive instead
<a ui-sref="login">login</a>
You should also use the ui-view directive to show the state your are targeting to.
The official docs contains short, simple tutorials that will help you getting started.
I have this in my Login.cshtml
<div class="contact-widget" data-loader="button">
<div ng-view>
</div>
</div>
and to change the view I have this:
<ul class="one-page-menu">
<li class="current"><div>Create Account</div></li>
<li><div>Login</div></li>
</ul>
in my app.js, I have this:
app.config(["$routeProvider", function($routeProvider) {
$routeProvider
.when("/Login", {
templateUrl: "/Partials/LoginPartial.html",
controller: "LogInController"
})
.when("/CreateAccount", {
templateUrl: "/Partials/CreateAccountPartial.html",
controller: "CreateAccountController"
})
.otherwise({ redirectTo: "/Login" });
}])
this is in my controller to view the login
public class LoginController : Controller
{
// GET: Login
public ActionResult Login()
{
return View();
}
}
When I click on the Login link to view the login form I get this in the Url http://localhost:18223/Login/Login/#!/Login and when I click the createaccount link I get this http://localhost:18223/Login/Login/#!/CreateAccount
but I can see the view change. My problem is; how do I make the Url get to be like this http://localhost:18223/Login/Login for both loginview and createaccount view
I am working on a AngularJs project where I have a Login page and Home page (all other pages will use the same home page view). Now I need to redirect the user from Login page (different layout) to Home page (another different layout).
Right now I have a Index page which contains both ng-app & ng-view tags and my Login page is getting rendered on that but after successful login I don't know how to show my different layout view (Home page).
Also, I have seen many people saying that you can use ng-if to hide/show the required piece (which is placed in same page itself). So, I tried using the rootScope variable to show/hide the span/div before and after login & I worked well. But one thing I noticed in this method is, when I load the login page I was able to see the sidebar, topbar & bottompanel for few seconds but they eventually become invisible and it looks messy.
My app.js:
$stateProvider
.state('login', {
url: "/login",
templateUrl: "/app/views/login/login.html",
controller: "loginController"
})
.state('home', {
url: "/home",
templateUrl: "/app/views/home/home.html",
controller: "homeController"
})
My login page: Very simple page - Contains just two textboxes and a button. When clicking the Login button loginController's login method will be called.
My home page: Very complex page - Contains a side panel, top panel, center panel (where all other views will be displayed) and bottom panel.
I have tried ng-if in the index page to show/hide login and home page using a rootScope variable (called isLoginSuccessful)
My Index page:
<html data-ng-app="myApp">
<body>
<div class="sidebar" id="sidebar" ng-if="isLoginSuccessful">
</div>
<div class="topbar" id="topbar" ng-if="isLoginSuccessful">
</div>
<div class="contentpanel" id="contentpanel">
<div ng-view>
<!-- view goes here-->
</div>
</div>
<div class="bottompanel" id="bottompanel" ng-if="isLoginSuccessful">
</div>
</body>
</html>
My loginController.js:
myApp.controller('loginController', ["$scope", "$rootScope", "$location", function ($scope, $rootScope, $location) {
$rootScope.loggedIn = false;
$scope.login = function () {
//do user validation check here
$rootScope.loggedIn = true;
$location.path("/home"); //redirect to home page
}
}]);
Is there any better way to handle this. Please help me.
Thanks in advance.
You asked how you navigate from the login page to the home page once you have logged in? Your logic is nearly there in the controller, and you have the states already set up, so alter it like so:
myApp.controller('loginController', ["$scope", "$rootScope", "$state", function ($scope, $rootScope, $state) {
$rootScope.loggedIn = false;
$scope.login = function () {
//do user validation check here
$rootScope.loggedIn = true;
$state.go('home'); //redirect to home page
}
}]);
Since the templates contain everything you need, you can get rid of the ng-if attributes since the only way they can navigate to the home page is via the login (and via the $state.go())
The best approach is to use Angular UI router. Take a look here https://angular-ui.github.io/ui-router/
EDIT:
It should work:
app.js
$stateProvider
.state('login', {
url: "/login",
views: {
"content#": {
templateUrl: "/app/views/login/login.html",
controller: "loginController"
}
}
})
.state('home', {
url: "/home",
views: {
"sidebar#": {
templateUrl: "/app/views/home/sidebar.html",
controller: "sidebarController"
},
"topbar#": {
templateUrl: "/app/views/home/topbar.html",
controller: "topbarController"
},
"content#": {
templateUrl: "/app/views/home/home.html",
controller: "homeController"
}
"bottompanel#": {
templateUrl: "/app/views/home/bottompanel.html",
controller: "bottompanelController"
}
}
})
index.html
<html data-ng-app="myApp">
<body>
<div class="contentpanel" id="contentpanel">
<div ui-view="sidebar"></div>
<div ui-view="topbar"></div>
<div ui-view="content"></div>
<div ui-view="bottompanel"></div>
</div>
</body>
</html>
loginController.js
myApp.controller('loginController', ["$scope", "$rootScope", "$state",
function ($scope, $rootScope, $state) {
$rootScope.loggedIn = false;
$scope.login = function () {
//do user validation check here
$rootScope.loggedIn = true;
$state.go("home"); //redirect to home page
}
}]);