Angular routing not working with ASP.Net MVC - angularjs

Home page I am using AngularJS with my ASP.Net MVC application and I am using angular routing but it is not working.
The angular routes are defined as:
var app = angular.module("webApp",['ngRoute']);
app.config(function($routeProvider){
$routeProvider.when(
"/",{
templateUrl: "home/dashboard",
controller: "webCtrl"
})
.when(
"/page1",{
templateUrl: "home/contact",
controller: "page1Ctrl"
})
.otherwise({
templateUrl: "home/contact",
controller: "page1Ctrl"
});
});
The navigation links are displayed on index.cshtml as given below:
<body ng-app="webApp">
Home
Page1
<div ng-view></div>
</body>
It displays dashboard when launched but doesn't display contact page when second link is clicked. Also, it displays strange URLs. On the homepage it dislays http://localhost:58193/#!/ and when I click on page1 link URL gets changed to http://localhost:58193/#!/#%2Fpage1.Please let me know if I am mistaking anything.

have you tried to do like this?
var app = angular.module("webApp",['ngRoute']);
app.config(function($routeProvider){
$routeProvider.when(
"/",{
templateUrl: "/home/dashboard",
controller: "webCtrl"
})
.when(
"/page1",{
templateUrl: "/home/contact",
controller: "page1Ctrl"
});
$routeProvider.otherwise({ redirectTo: "/page1" });
$locationProvider.hashPrefix("!");
});
then:
<body ng-app="webApp">
<a ng-href="#!page1">Page1</a>
<div ng-view></div>
</body>
and maybe put in your index-html in your section this:
<meta name="fragment" content="!">
<base href="/">

Related

angularjs ngRoute not working

ngRoute not working while no errors are reported to console .
given no errors to console, how is it possible to follow execution of ngRoute procedures ?
i saw examples using $locationProvider.html5Mode(true), i don't understand when that should be used but i don't think it is required to make ngRoute work.
index.html has navigation links and ngView :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="bower_components/angular/angular.js"> </script>
<script src="bower_components/angular-route/angular-route.js"> </script>
<script src="main.js"> </script>
</head>
<body ng-app="Main">
<ul>
<li> first partial </li>
<li> second partial </li>
</ul>
<div ng-view></div>
</body>
</html>
main.js defines the router and the controllers :
var Main = angular.module('Main', ['ngRoute']);
function router($routeProvider) {
var route = {templateUrl: 'partials/default.html'};
$routeProvider.when('', route);
route = {
templateUrl: 'partials/first.html',
controller: 'first'
};
$routeProvider.when('content/first', route);
route = {
templateUrl: 'partials/second.html',
controller: 'second'
};
$routeProvider.when('content/second', route);
}
Main.config(['$routeProvider', router]);
Main.controller('first', function($scope) {
$scope.list = [1,2,3,4,5];
});
Main.controller('second', function($scope) {
$scope.list = [1,2,3];
});
partials simply make use of ngRepeat:
<header> First content </header>
<p ng-repeat="iter in list">
first
</p>
solved :
my problem was that my whole application is located under /ang/ prefix, and after adding that prefix to urls now it is working .
shouldn't there be a way to use relative urls ? i guess there should and i will try to fix it .
the problem is NOT with the different syntax as everyone suggested, and that is alarming to the fact many JS developer do not in fact understand the one line syntax that they are using everywhere .
Please check this code
HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-route.js"> </script>
<script src="script.js"> </script>
</head>
<body ng-app="Main">
<ul>
<li> first partial </li>
<li> second partial </li>
</ul>
<div ng-view></div>
</body>
</html>
Js file
var app = angular.module('Main', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
when('/content/first', {
templateUrl: 'first.html',
controller: 'first'
}).
when('/content/second', {
templateUrl: 'second.html',
controller: 'second'
});
}]);
app.controller('first', function($scope) {
$scope.list = [1,2,3,4,5];
});
app.controller('second', function($scope) {
$scope.list = [1,2,3];
});
first page HTML
<header> First content </header>
<p ng-repeat="item in list">
{{item}}
</p>
here is your working code click
Do not reuse the route object as it might cause problems. Consider using it in the form (as suggested by the docs https://docs.angularjs.org/api/ngRoute/service/$route#example ):
$routeProvider
.when('content/second', {
templateUrl: 'partials/second.html',
controller: 'second'
});
If you want to debug the routes that angular goes through, you might want to look at angular's interceptors: https://docs.angularjs.org/api/ng/service/$http#interceptors
Also, $locationProvider.html5Mode(true) is not needed to make ngRoute work. It is simply a way of defining how the URLs should look like and work. in HTML mode you can change the links to not use # anymore and simply be www.yoursite.com/app/content/second instead of www.yoursite.com/app#content/second
your route configuration is not correct, you assume route function is execute for each and every link u click but its not.
so your route function should be like
function router($routeProvider) {
$routeProvider.
when('/content/first', {
templateUrl: 'partials/first.html',
controller: 'first'
}).
when('/content/second', {
templateUrl: 'partials/second.html',
controller: 'second'
}).
otherwise({
templateUrl: 'partials/default.html'
});
}
note that urls should be like <a href="#/content/first"> // note the slash after #
to match that the routes in route function should be like when('/content/first', { note the leading slash
here is the working Plunker
Define your Routes in routes.js
var route = angular.module('route', ['ngRoute']);
route.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "views/home.html",
controller : 'homeCtrl'
})
.when("/home", {
templateUrl: "views/home.html",
controller : 'homeCtrl'
})
.when("/product", {
templateUrl: "views/product-info.html"
})
.otherwise({redirectTo :'/'});
});
Attach the router to your Main Module.
angular.module('myApp', ['route']);
Import both the scripts in your index.html

Converting AngularJS to ASP.NET MVC

I am currently converting an AngularJS HTML app to ASP.NET MVC and I have laid out pretty much everything and but when the page loads I see the controller(dashboard.js) but its not firing any function from the dashboard controller here is what I'm doing:
in my _layout.cshtml I have the following:
<html ng-app="app_angular" >
<head>
<script src="~/script/angular/angular.js"></script>
<script src="~/script/angular/angular-route.js"></script>
<script src="~/script/angular/angular-resource.js"></script>
<script src="~/script/angular/angular-animate.js"></script>
<script src="~/script/angular/angular-cookies.js"></script>
<script src="~/script/js/jquery.min.js"></script>
<script src="~/script/js/bootstrap.min.js"></script>
<script src="~/Scripts/myapp.js"></script>
<script src="~/Scripts/controllers/dashboard.js"></script>
<script src="~/Scripts/routes.js"></script>
</head>
<body>
<ng-view class="fx fx-slide page"></ng-view>
<div class="container">
<h3 class="row title">
<div class="col-xs-6">Dashboard</div>
<div class="col-xs-6 text-right text-gray">{{ today | date:'MMMM d, y' }}</div>
</h3>
</div>
<section ng-repeat="template in templates">
<ng-include src="template"></ng-include>
</section>
<div class="container" ng-init="init()">
<!-- Buttons -->
</body>
</html>
myapp.js
var app_angular = angular.module('app_angular', ['ngCookies', 'ngRoute', 'ngResource', 'ngAnimate']);
dashboard.js
'use strict';
app_angular
.controller('dashboard', function ($rootScope, $scope) {
debugger
$scope.today = new Date();
/* set template subviews */
$scope.templates = {
stream: "../../views/templates/firstqtr.html",
modal: "../../views/templates/secondqtr.html",
loan: "../../views/templates/thirdqtr.html"
};
});
routes.js(first approach: does not work)
app_angular
.config(function($routeProvider, $httpProvider) {
$routeProvider
/* dashboard */
.when('/', {
controller: 'dashboard',
templateUrl: '../../views/home/index'
})
.when('/home/about', {
controller: 'dashboard',
templateUrl: '../../views/home/about'
})
.otherwise({
redirectTo: '/'
});
});
routes.js(second approach: does not work)
app_angular
.config(['$routeProvider', function ($routeProvider)
{
$routeProvider
.when('/', { templateUrl: '/home/index', controller: 'dashboard' })
.when('/', { templateUrl: '/home/about', controller: 'dashboard' })
.otherwise({ redirectTo: '/home' });
}])
What else I should be doing any help?
Assuming that /home is the path of your MVC page
you should change your angular routing to use path's that are
relative to your page.
add a view templates that are loaded into your
page
the angular routing below would:
load your mvc page /home/index and inject the template dashboard.html into ng-view element
(MVC controller Home with Action Index is required)
load your mvc page /home/index and inject the template about.html into ng-view element
Routes:
app_angular
.config(function ($routeProvider, $httpProvider) {
$routeProvider
/* dashboard */
.when('/', {
controller: 'dashboard',
templateUrl: '../../views/templates/dashboard.html'
})
.when('/about', {
controller: 'dashboard',
templateUrl: '../../views/templates/about.html'
})
.otherwise({
redirectTo: '/'
});
});
Remark:
You should rethink your approach of mixing MVC and anjularjs that not a good approach.
Try renaming your _layout.cshtml into index.html and start with a plain (ASP.NET MVC free) SPA.
Files:
index.html
views\dashboard.html
views\about.html
Routes:
app_angular
.config(function ($routeProvider, $httpProvider) {
$routeProvider
/* dashboard */
.when('/', {
controller: 'dashboard',
templateUrl: 'views/dashboard.html'
})
.when('/about', {
controller: 'dashboard',
templateUrl: '/views/about.html'
})
.otherwise({
redirectTo: '/'
});
});

How do I implement page navigation in AngularJS?

i have two html pages which are named main.html and detail.html. When click the link button in main,i wanna open detail page for details.
Main.html:
<body ng-app="MyApp" ng-controller="mainController">
<div data-role="page" data-theme="b">
<a ng-href="detail.html"></a>
</div>
</body>
detail.html:
<div data-role="page" data-theme="b" ng-controller="DetailContoller">
<button>{{a}}</button></div>
Contoller:
MyApp.controller("mainController", function ($scope, $http, OranService, $location) {
$scope.a = 5;
$scope.items = [];});
MyApp.controller('DetailController', function ($scope, OranService) {
$scope.a = 1;});
When Click the link button in the main page, i see only a button which text {{a}}, and my url:'localhost/Main.html'. I dont want use target=_self vs. if i use ,when return click button press, main page will reload.
Do you have any suggestion?
Thanks!
Looks like you're mixing jQuery Mobile and Angular notation.
To implement navigation in Angular you can use the core Angular service $routeProvider. You have to include the ng-route module for this.
Here's an example of how to config this on your module:
angular.module('app', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/page1', {
templateUrl: 'page1.html',
controller: 'Page1Ctrl'
})
.when('/page2', {
templateUrl: 'page2.html',
controller: 'Page2Ctrl'
})
.otherwise({
redirectTo: '/page1'
});
}]);
Now in your html, use the directive ng-view to specify the tag that should contain the template.
<body ng-app="app">
<div ng-view>
</div>
</body>

angularjs ui-router strange behaviour with additional segment in route

I'm suffering a problem with ui-router when I add a wrong segment to the route.
An example... http://xxx.xxxxx.xxx/roles works fine. This is a route defined without parameters. But if I add another segment in the browse http://xxx.xxxxx.xxx/roles/kk the $urlRouteProvider.otherwise('/') does not work and the application is trying to load all web resources (css, html, javascript, etc.) from a route like http://xxx.xxxxx.xxx/roles/app/app.css returning a lot of errors in console.
This code is in my app.config:
$urlRouterProvider
.otherwise('/');
$locationProvider.html5Mode(true);
And this is an example of route definition:
angular.module('myApp')
.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('roles', {
url: '/roles',
templateUrl: 'app/modules/admin/roles/index.html',
controller: 'RolesCtrl',
authenticate: true
})
.state('logs', {
url: '/logs',
templateUrl: 'app/modules/admin/logs/index.html',
controller: 'LogsCtrl',
authenticate: true
})
.state('parameters', {
url: '/parameters',
templateUrl: 'app/modules/admin/parameters/parameters.html',
controller: 'ParametersCtrl',
authenticate: true
});
}]);
Any help with this behavior?
Regards
Jose
Not fully sure where is theissue here... but I created working plunker, which should help to see what is needed to see the HTML 5 and ui-router working together. In case that server side is configured properly, this should work out of the box. Please, check this firstly:
How to: Configure your server to work with html5Mode
Now, this would be adjusted state def, to show the deep url nesting:
$stateProvider
.state('roles', {
url: '/roles/:id',
...
})
.state('roles.logs', {
url: '/logs',
...
})
.state('roles.logs.parameters', {
url: '/parameters',
...
});
To make all these call below wroking:
<nav>
roles/11/<br />
roles/22/logs<br />
roles/33/logs/parameters<br />
</nav>
<nav>
<a ui-sref="roles({id:1})">roles </a><br />
<a ui-sref="roles.logs({id:2})">roles.logs</a><br />
<a ui-sref="roles.logs.parameters({id:3})">roles.logs.parameters</a><br />
</nav>
we have to not forget to properly set the base url, in our example:
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
...
<base href="/cTRk4o9HRELCQ4OK/" />
But for plunker we should set that dynamically:
<script>
document.write('<base href="'+ document.location.pathname +'" />')
</script>
Check working example here
You also have to define an state that points to the otherwise url, this way UI Routers knows how to handle the default state.
var app = angular.module('demo', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('roles', {
url: '/roles',
templateUrl: 'roles.html'
})
.state('otherwise', {
url: '/',
templateUrl: 'otherwise.html'
})
$urlRouterProvider
.otherwise('/');
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://rawgit.com/angular-ui/ui-router/0.2.11/release/angular-ui-router.js"></script>
<div ng-app="demo">
<ul>
<li>Roles</li>
<li>Otherwise</li>
<li>Not Found</li>
</ul>
<ui-view></ui-view>
<script type="text/ng-template" id="roles.html">
<h2>Roles Template</h2>
</script>
<script type="text/ng-template" id="otherwise.html">
<h2>Otherwise Template</h2>
</script>
</div>

Route to new base page

In angular I have defined my routes like this:
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {templateUrl: 'pages/main.html', controller: 'MainController'});
$routeProvider.when('/login', {templateUrl: 'pages/login.html', controller: 'AccountController'});
$routeProvider.otherwise({redirectTo: '/'});
}]);
So my web site loads the pages/main.html page inside my index.html. When I goto #/login then my pages/login.html inside index.html.
But I actually don't want to load page/login.html inside index.html. I want my login page to have its own layout.
So is there a way to load login.html in such a way so that it's not included inside index.html as a partial, but so that it can have it's own base layout?
Yes you could create new html page for login page so it could use bage template
for eg:
base-template.html
<html>
<head>Your scripts</head>
<body ng-app="yourmodule">
<ng-view></ng-view>
</body>
</html>
create login.html
<div>
First Name:<input type="text"/>
Last Name:<input type="password"/>
</div>
var app = angular.module("Your module",[ngroute]);
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'login.html',
controller:'your controller'
});
app.controller("Your controller",function($scope){
//your logic
});
Hope it helps you

Resources