Angular MVC Routing with Custom Controller - angularjs

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'
});
}]);

Related

Spring, Angular Js

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'
})

Why first page load is slow with ASP.MVC + AngularJS

I have an application with ASP.NET MVC and AngularJS.
My route are manage by AngularJS with ui-router.
The first time AngularJS load the partialview it's more slow then the second. What causes this ?
There are my codes:
AngularJS
app.config(function ($httpProvider, $urlRouterProvider, $locationProvider, $stateProvider) {
$urlRouterProvider.otherwise('/home');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$locationProvider.html5Mode(true);
var homeState = {
name: 'home',
url:'/home',
controller: 'HomeCtrl',
controllerAs:'vm',
templateUrl:'/AngularJS/Home/Home' //AngularJS is a Area/Controler/Method
}
var loginState = {
name: 'login',
url: '/login',
controller: 'LoginCtrl',
controllerAs: 'vm',
templateUrl: '/AngularJS/Home/Login'
}
var registrationState = {
name: 'registration',
url: '/registration',
controller: 'RegistrationCtrl',
controllerAs: 'vm',
templateUrl: '/AngularJS/Home/Registration'
}
var dashboardState = {
name: 'dashboard',
url: '/dashboard',
controller: 'DashboardCtrl',
controllerAs: 'vm',
templateUrl: '/AngularJS/Home/Dashboard'
}
...
$stateProvider.state(homeState);
$stateProvider.state(loginState);
$stateProvider.state(registrationState);
$stateProvider.state(dashboardState);
$stateProvider.state(gameState);
$stateProvider.state(userState);
$stateProvider.state(newGameState);
$stateProvider.state(platformState);
$stateProvider.state(unavailabilityState);
$stateProvider.state(teamsState);
$stateProvider.state(newTeamState);
$stateProvider.state(editTeamState);
$stateProvider.state(detailTeamState);
$httpProvider.interceptors.push(requestInterceptor);
})
ASP.NET MVC
public PartialViewResult Home()
{
ViewBag.Title = "Home";
return PartialView();
}
public PartialViewResult Login()
{
ViewBag.Title = "Login";
return PartialView();
}
public PartialViewResult Registration()
{
ViewBag.Title = "Registration";
return PartialView();
}
public PartialViewResult Dashboard()
{
ViewBag.Title = "Dashboard";
return PartialView();
}
...
Exemple load time:
First
Second
application might be trying to load large resource that you have added to template, one way of find it is using Chrome browser (it also available in other browsers as well) follow bellow steps,
right click on the page go to Inspect element and select Network tab as bellow.
there you can see the time that took to load each resources , when its getting higher , site will take more time to load

Angular Routing with Asp.net mvc areas and cshtml not working

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!

how does todo mvc example for angularjs do without ng-controller?

Every example I've looked at has made use of the ng-controller directive to get things working.
The Todo MVC example at https://github.com/tastejs/todomvc/tree/gh-pages/examples/angularjs creates a 'TodoCtrl' controller. But in the corresponding index.html, there is no use of the ng-controller directive.
How is this possible? and why did they choose to do it this way?
It uses the ngRoute provider.
angular.module('todomvc', ['ngRoute'])
.config(function ($routeProvider) {
'use strict';
var routeConfig = {
controller: 'TodoCtrl',//add controller to view
templateUrl: 'todomvc-index.html',
resolve: {
store: function (todoStorage) {
// Get the correct module (API or localStorage).
return todoStorage.then(function (module) {
module.get(); // Fetch the todo records in the background.
return module;
});
}
}
};
$routeProvider
.when('/', routeConfig)
.when('/:status', routeConfig)
.otherwise({
redirectTo: '/'
});
});

Controlling multiple views in one controller in AngularJS

Following the MVC pattern, one controller should be able to handle multiple views in AngularJS.
E.g. I have one view for showing all users and one for creating a new user. My $routeProvider (excerpt) looks like this:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/showusers', {
templateUrl: 'partials/showusers.html',
controller: 'userController'
}).
when('/createuser', {
templateUrl: 'partials/showusers.html',
controller: 'userController'
})
}]);
Both views share several methods such as retrieving all user attributes. These shared methods are accessed through a factory.
The userController (excerpt) currently looks like this where Users is a factory:
angular.module('supportModule').
controller('userController', function($scope, Users) {
var init = function(){
$scope.users = Users.getAll();
$scope.attributes = Users.getAttributes();
}
init();
})
The problem is: I don't need to request Users.getAll(); when I'm on the createuser view.
Of course, I could easily parse the route by using $location, the $routeProvider or pure JS and then conditonally call methods - but I figure there is a more elegant and efficient way in Angular :)
Something like in typical MVC frameworks where one controller has many actions - one for each view.
So my question:
How to elegantly call methods based on the view in a controller which controls more than one view?
You could use resolve: when setup $routeProvider to pass values to a controller depending on the matched route.
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/showusers', {
templateUrl: 'partials/showusers.html',
controller: 'userController',
resolve: {
ctrlOptions: function () {
return {
getAllUsers: true,
};
}
}
}).
when('/createuser', {
templateUrl: 'partials/showusers.html',
controller: 'userController',
resolve: {
ctrlOptions: function () {
return {
getAllUsers: false,
};
}
}
})
}]);
and then in the controller, you can inject item specified in resolve: like this:
app.controller('userController', function ($scope, Users, ctrlOptions) {
var init = function () {
if (ctrlOptions.getAllUsers) {
$scope.users = Users.getAll();
}
$scope.attributes = Users.getAttributes();
};
init();
});
Hope this helps.

Resources