I'm having some trouble with routing in Angular.js and MVC5. I've simplified it down to the example below.
My angular routing code is:
app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
$routeProvider.when("/", {
template: "<h1>index</h1>",
})
.when("/Home/About", {
template: "<h1>about</h1>",
})
.when("/Home/Contact", {
template: "<h1>contact</h1>",
})
.otherwise({
template: "<h1>Error</h1>",
});
}]);
The MVC Home controller has a method for each, and each view has a DIV with ng-view attribute.
When I browse to either about or contact the route is still mapping to Index.
If I change the index path to :
$routeProvider.when("/Home/Index", {
template: "<h1>index</h1>",
})
then Otherwise kicks in and I see Error.
The code looks identical to other angular code I've used, and examples on the web. Any suggestions?
Updated: Thanks to the answers below. I think I didn't explain my problem well last night, the result of a long day. My problem is that I'm trying to have a mini-spa on a sub page of the site, so the route for the main page would be:
.when("/userPermissions/index", {
templateUrl: "/scripts/bookApp/userPermissions/main.html",
controller: "userPermissionController",
})
And the path of "/userPermissions/index" which would be the page provided by the server isn't being matched by the routing.
Angular is by design a Single Page Application (SPA) framework. It is designed to process requests within a single server page request, and handle route changes without making subsequent calls to the server. Hence, for every page load, the page is at the "root" of the application. or /, no matter what path was used on the server to load the page.
Subsequent page loads and routing are handled using the 'hash' notation /#/someroute in order to suppress a browser reload. Thus, the actual route being matched by the angular $routeProvider is http://example.com/#/Home/About, but this is loaded from the / server route.
If you redirect the page to /Home/About on the server, but still want to get to that match in Angular, then the route would be http://example.com/Home/About#/Home/About. Quite problematic, as you can imagine.
HTML5 Routing Mode can be used to remove the #/ from your routes, Allowing you to match http://example.com/Home/About in the Angular $routeProvider. But, for Angular to really shine, you should also configure Rewrites on your server, and not handle these Routes as separate views in your ASP.Net application. Generally, you will have a much cleaner solution if you can restrict server communications to API calls, as mixing Server HTML (or Razor) with Client Side Angular gets very confusing very fast.
I would suggest you to create one base for your angular SPA.
That means you will need to create a C# controller inside your application that will have one action i.e. Index
SPAController.cs
using System.Web.Mvc;
namespace AngularApp.Controllers
{
public class SPAController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Views/SPA/Index
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<div ng-view></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>
Now all is set hit html ng-view will load partial view by watching route.
Hit in browser http://anything.com/spa/#/. Then your angular app will start working on page.
I would not suggest you to use html5mode() inside MVC app. That will create many problem inside your app. And it will take more time to manipulate things.
Thanks.
Related
I am building a custom angular app in Grails, but sticking as much as possible to the default Grails Controller View behaviour.
What I'm trying to do is: using the scaffolding controller. Get the same behaviour but by ading a #/ to the start of the url. So that after you save a Record, you'd be redirected to:
http://localhost:8080/#/country/show/5
instead of
http://localhost:8080/country/show/5
So that Angular kicks in again. I know this isn't the standard Angular behaviour but I'm trying to use as few angular files as possible since I have very little knowledge in angular.
The default scaffolding redirect is:
redirect country
And I tried using:
redirect base: "#/", country
redirect country, [base: "#/"]
redirect country, base: "#/"
redirect absolute: "#/", country
But they all throw 500 error when called.
This is my current app config in angular:
app.config(function($routeProvider) {
$routeProvider.when("/:controller/:action",{
templateUrl:function(params){
return '/'+params.controller+'/'+params.action;
}
})
.when("/:controller/:action/:param",{
templateUrl:function(params){
return '/'+params.controller+'/'+params.action+'/'+params.param;
}
});
});
Have you tried this?
class SomeController {
LinkGenerator linkGenerator
def action() {
redirect uri: linkGenerator.link(
controller: 'country', action: 'show', id: 5, base: '/#')
}
}
UPDATE: Given the requirement to support multiple formats, teaching angular to work with "pretty" URLs might be the only way. Here is an example posting that has the following code:
angular.module('scotchy', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
controller : mainController
})
.when('/about', {
templateUrl : 'partials/about.html',
controller : mainController
})
.when('/contact', {
templateUrl : 'partials/contact.html',
controller : mainController
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
I ended up giving up on angular entirely. To show the views inside a dialog I just extract the html segment from the response returned from the server and I get all the default behaviour that Grails includes out of the box.
Since grails is a full stack framework and it's front end is highly customizable. Unless you want to build an entire angular app it's not worth replacing the front end with angular just for it's single view capabilities.
The server responses may be slightly bigger than what I need to show inside a dialog, but it doesn't hurt performance. And the controllers don't know if their views are being rendered inside a dialog or as a full web page, which is what I wanted in the first place.
I have a rails app with dashboard page. So the page will be http://mywebsite.com/dashboard. It has few links available which will load pages via ajax and show it in a div section inside the dashboard page. Its all working fine. So lets assume I want to use angular here and I specify code like below.
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html"
})
})
My doubt is that:
So in here if dashboard is the root url then the url generated is http://mywebsite.com/#route1
What if my dashboard page is defined like this
http://mywebsite.com/dashboard and I want to define route like http://mywebsite.com/dashboard/#route1
Note: Its not a single page application. But I want the dashboard page
to be like a single page one..
This will work fine and the route will be relative to your URL
http://mywebsite.com/dashboard.
If you were using HTML5 mode with Angular UI router if you try and interoperate the full URL. But because you are not using HTML5 mode, Angular UI router routes using #.
I'm a web app developer with ASP.NET MVC 5 in server-side and AngularJS in client-side. The navigation, in client-side, is managed with module UI-Router. In server-side I've configured my custom authentication and authorization. When I excecute the app can see a navigation bar with many links. In particular, I have a link named "Overview" that redirects to controller Overview.
Code client (html):
<a ui-sref="Overview">Overview</a>
Code client to redirect (angular):
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("Home/Index");
$stateProvider
.state("Overview", {
templateUrl: "Home/Overview",
url: "/overview"
})
Controller code:
[OutputCache(Duration=0, NoStore=true)]
[AllowAnonymous]
public ActionResult Overview()
{
return PartialView();
}
With a breakpoint in line "return PartialView()" to controller code, I can see that controller returns partial view when I click over "overview" in menu app. But when I click second time, the breakpoint does not trigger. I think it's a caching issue.
I have read that caching issue can be generated:
* In server-side.
* In client-side.
* Even IIS.
I have tried many solutions: In server side I use attribute [OutputCache].
When i read in my browser the http headers i can see
In client side i could not find a solution to avoid caching, but i think that UI-Router shouldn't cache anything.
As additional measures I put in my web.config:
<system.webServer>
<caching enabled="false" enableKernelCache="false" />
</system.webServer>
even, I created my own custom ActionFilterAttribute but did not work.
i don't know what else to do.
PS: sorry for my english
If there is any other plugin which does caches its templates, then your solution will clean those templates and make those plugins unusable.. hence your solution is not good.
To solve problem of html caching you should add random query string at the end of html filename... the other solutions you mentioned are for non-caching of api responses and not for static content (html/js/css files)
To add random query string to ur html. either you can use modules like grunt-cache-busting or gulp-rev or use query string as param query-string-cache-busting.
Please note that datetime/file-hash are best cache-busting param
Ok, I've found the solution.
Despite avoid caching from server side with attributes like OutputCache, or avoid caching from IIS setting my web.config, the issue persisted.
AngularJS was the guilty. In other post I found the solution.
myApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
This solution is provided by Mark Rajcok and Valentyn Shybanov. So thanks to both.
I have a Rails application in which I am trying to replace some views with AngularJS, but not all. In each view I replace, I want it to basically act as if it is it's own SPA. I am also trying to use ui-router to manage states within each of these SPAs.
For example, I have a Rails route that maps to a view ".../checkout/1. This triggers a Rails view in which I load the initial SPA for the flow and then let angular take over. I would like to setup ui-router states that are just specific to this checkout flow.
Where I am getting stuck is how to have states that are only specific for that flow with that base url. If I setup the states:
$stateProvider
.state('start', {
url: "/",
templateUrl: "..."
})
.state('route2', {
url: "/route2",
templateUrl: "..."
})
.state('route3', {
url: "/route3",
templateUrl: "..."
});
This works and for .../checkout/1#/, .../checkout/1#/route2, .../checkout/1#/route3.
However, it also work in my other SPA views which I do not want. So, if I do another rails view that uses another SPA, e.g. .../item/1 then the above route will also work for .../item/1#/ and .../item/1#/route2, etc.
Instead, I would like each to be it's own SPA and not conflict with each other. I am not sure how to do this. Can ui-router be somehow namespaced using the base url or can I have independent SPAs that have different stateProviders? Any thoughts on how I should go about this?
Thanks
Each SPA should have its own angular module defining an application with its own state definitions. So there can't be any conflict.
I'm totally new to AngularJS. Just wanted to try out relative URLs with $routeProvider.
Here is the scenario:
I have a "Edit" page, the ASP.NET MVC link to the page would be:
http://localhost/Workflow/Edit
So the ASP.NET MVC Controller is "WorkflowController" and the action is "Edit". For the Partials I have Controller actions that each return a Partial View like this:
public ActionResult WorkflowTransition()
{
return PartialView("WorkflowTransition");
}
public ActionResult WorkflowTransitionApprovers()
{
return PartialView("WorkflowTransitionApprovers");
}
Following is the AngularJS module configuration - note: a PartialView (as mentioned above) is called for each of the routes (this could be incorrect):
$routeProvider.when('Workflow/WorkflowTransition', {
templateUrl: '/Workflow/WorkflowTransition',
controller: 'transitionCtrl',
});
$routeProvider.when('Workflow/WorkflowTransitionApprovers', {
templateUrl: '/Workflow/WorkflowTransitionApprovers',
controller: 'approversCtrl'
$routeProvider.otherwise({
redirectTo: '/'
});
Note: I have not specified either of the following:
$locationProvider.html5Mode(false);
OR
$locationProvider.html5Mode(false).hashPrefix('!');
The href links are specified like this:
{{workflow.Identifier}}
This generates links of this form:
http://localhost/Workflow/Edit#/Workflow/WorkflowTransition
This is obviously wrong (and clicking the link doesn't do anything probably because the browser tried to navigate to the hash), so I have tried the leading '/', but no luck there too:
{{workflow.Identifier}}
If I navigate the partial directly i.e. http://localhost/Workflow/WorkflowTransition, the browser renders the html as-is (along with the angularjs curly braces {{}}).
My question is: How does AngularJS treat the '#' or '#!' when it comes to determining relative URLs? For e.g. does this route (assuming I knock off the /Edit part from the URL in the anchor tag):
$routeProvider.when('Workflow/WorkflowTransition', match the URL:
http://localhost/Workflow/#WorkflowTransition ?
Does it remove the '#' from the URL and then check it against the URL pattern in $routeProvider.when() ?
Can someone please suggest correct routes for the relative URLs?
From my observation, the hash has to be removed when matching routes. I have a link like
<a href="#Objects">
resulting in the URL
http://localhost:55033/#/Objects
My route Setup is
$routeProvider.when("/Objects", {
templateUrl: "objects.html",
controller: ObjectCtrl
});
And this works as expected, pulling in the correct partial. Note that I am not Rendering partials through ASP.NET MVC Controllers in this case. Instead I have objects.html lying around as plain html file and I am using the hash in the href so the ASP.NET MVC Routing does not kick in.
Routeprovide should be setup like below.
$routeProvider.when('/Workflow/WorkflowTransition', {
templateUrl: "WorkflowTransition.html",
controller: WorkflowTransitionCtrl
});
and URL should be enter in below formate.
http://localhost/#/Workflow/WorkflowTransition ?