Am using Angular1.5 with asp.net mvc.
By default when my application loads it points to http://domainname/components/Webui/Home/Instructions
Home - controller,
Instructions - Action
public class HomeController : Controller
{
public ActionResult Instructions()
{
return View();
}
}
above url returns an html
which contains below
<div>
<div ng-include src="app/Layout/shell/Shell.html" class="height100">
</div>
</div>
But it is not able to download the shell.html.
it is generating the wrong url as below
http://domainname/components/Webui/Home/app/layout/shell/Shell.html
In the above url why Home is coming ?
My folder structure is
app
layout
shell
Shell.html
Controllers
Views
Home
Index.cshtml
Instructions.cshtm
Please correct me if anything is wrong.
You are using a relative path from index. Append forward slash to path to traverse from project root:
ng-include src="/app/Layout/shell/Shell.html
Related
I build a simple app with an index.jsp (as a welcome page) and after a form-login submission directly to spring controller, i return either index.jsp or homePage.jsp (when user credentials are valid). So angular (routes, components, etc) loads for the first time at homePage.jsp.
I chose this implementation due to the fact that i am allowed to use only one ng-view and i wanted to do this only at my homePage from the time that is my main content.I would like some suggestions without using a 3d party routing such as ui-router.
First submit you from from JSP page to Spring Controller
<form action = "/checkUser">
[Your input tags]
</form>
In Spring
#Controller
public class Login{
#RequestMapping("checkUser")
public String checkUser(#RequestBody Map<String,Object>){
[Check your user is Valid or not]
[If valid]
return "homePage.jsp"
[else]
return "Index.jsp"
}
}
But rather than this i personally prefer Spring Security.
Once you got on your homePage you can load all your necessary js file including the annular js files
And load your views using ng-Route
var app = angular.module('tester',
['ngRoute']).config(function($routeProvider) {
$routeProvider
.when('/tests', {
templateUrl: 'tests.html',
controller: 'TestCtrl'
});
});
app.controller('TestCtrl', ['$scope', function($scope){
$scope.title = "This is a Test Page";
}]);
When You click on Tests link
<div ng-view></div>
Test
tests.html will directly load in ng-view part
For ng-view Plunker
This question might sound very generic to some of you but as a newbie i am having trouble in this. Its evident to use ng-view within the home page in order to display other html files within the page but how should i redirect to a new page present in the web app. I mean how to route to completely different web page in a multipage web application.
Import AngularJs-Route File
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
Then you must add the ngRoute as a dependency in the application module:
var app = angular.module("myApp", ["ngRoute"]);
Use the $routeProvider to configure different routes in your application:
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
STructure Your HTML
<body ng-app="myApp">
<p>Home</p>
Red
Green
Blue
<div ng-view></div>
</body>
For nested views you can use https://github.com/angular-ui/ui-router
Follow https://github.com/angular-ui/ui-router/wiki/Nested-States-&-Nested-Views for reference
Try searching angular ui-roter how its works and its mechanism . Since angular is a single page application your app needs to be on one base template then expand from their. From base template route in different page but if you want to route to different application use normal hyper link or ui-serf . Go though u-router basic. Also look into ui-serf .
I am working with .net mvc and angular js.
HomeController
public ActionResult Index()
{
return View();
}
In angular controller there is a service to get all the item details
[HttpGet]
public JsonResult GetItemDetails()
{
// return item list
}
If I run the solution without opening HomeController in visual studio I found 404 error saying that resource is not found.
One more thing I have noticed in network is the called URL is "/Home/Home/GetItemDetails".
But when I open HomeController in visual studio everything will be working fine.
How it is happening ?
Make sure your routing values and the URL you called are one and the same.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
For this, the URL looks like /Home/Index
Verify the URL you are using in Angular and you may be adding the controller name twice somewhere.
$http.get("Home/GetItemDetails") this is the URL I had used to call controller method.
I missed slash in this
So the solution is $http.get("/Home/GetItemDetails")
Thank you.
So I have a simple application AngularJs and Spring mvc. I have a controlller that mapped to the angularJs page and I have this code in a jsp page :
<div ng-app="myApp" ng-controller="myCtrl">
<p>The name is <span ng-bind="person.lastName"></span></p>
{{ lastName }}
</div>
<script src="applications.js"></script>
<script src="controllers.js"></script>
application.js :
var app = angular.module("myApp", []);
controllers.js :
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});
when I run this with Pivotal it dosn't run, but when I access the file directly within my browser it works like a charm, Someone care to explain pls ?
Thank you.
EDIT
WebConfig.java :
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling ( DefaultServletHandlerConfigurer configurer )
{
configurer.enable();
}
}
resources folder :
The URL : http://localhost:8080/gestionprojet/Project/angularjs
My Controller :
#RequestMapping("/angularjs")
public String getAngularJs() {
return "AngularJs";
}
First of all, your files are under /WEB-INF/resources, but you have configured spring to load static resources from /resources. So they can't be served at all. The config should be
registry.addResourceHandler("/resources/**")
.addResourceLocations("/WEB-INF/resources/");
The URL of your page is
/gestionprojet/Project/angularjs
Your page tries to load the script using the relative path
applications.js
So the corresponding absolute path where the browser looks for the JS files is
/gestionprojet/Project/applications.js
which doesn't match with the URLs you choose to serve static resources from. Assuming /gestionprojet is the context path of the application, the absolute URL should be
/gestionprojet/resources/applications.js
So the source code in the JSP should thus be
<script src="${pageContext.request.contextPath}/resources/applications.js"></script>
I have a sample MVC6 single page app with one view in which I want to load 2 Angular partials using ngRoute. You can have a look at it at GitHub
There are 3 URLs in the app:
localhost - Index.cshtml
localhost/games - Index.cshtml with Angular's gamelist.html partial
localhost/games/2 - Index.cshtml with Angular's game.html partial
The routes config is the following:
MVC:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
routes.MapRoute("gamelist", "games", new { controller = "Home", action = "Index"});
routes.MapRoute("gameWithId", "games/2", new { controller = "Home", action = "Index" });
});
Angular:
myApp.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/games', {
templateUrl: 'partials/gameslist.html',
controller: 'GameController',
controllerAs: 'ctrl'
})
.when('/games/:gameId', {
templateUrl: 'partials/game.html',
controller: 'GameController',
controllerAs: 'ctrl'
});
$locationProvider.html5Mode(true);
}]);
It all works perfectly fine as long as I start the app from the home page '/' and then navigate to the partials using the links on the page. The problem is that the URL #3 (localhost/games/2) does not work if I start the app from it, by typing it in the address bar. The URL #2 (/games/) does work.
The reason why #3 does not work is that MVC removes '/games' part from the URL and what Angular gets is just '/2'. If you run the sample app, you will see that '$location.path = /2'. Of course Angular cannot map using that path and no partial is rendered. So my question is - how to make MVC return the full path to the client so that Angular can map it?
You can get it to work with HTML5 mode, you just need to ensure that every request maps back to your Index.cshtml view. At that point the AngularJS framework loads, client-side routing kicks in and evaluates the request URI and loads the appropriate controller and view.
We've done this with multiple Angular apps inside MVC with different .cshtml pages, though we use attribute routing with the wildcard character, e.g.
[Route("{*anything}")]
public ActionResult Index()
{
return View("Index");
}
The wildcard operator (*) tells the routing engine that the rest of the URI should be matched to the anything parameter.
I haven't had chance to get to grips with MVC6 yet but I think you can do something like this with the "new" version of attribute routing?
[HttpGet("{*anything:regex(^(.*)?$)}"]
public ActionResult Index()
{
return View("Index");
}
To make link #3 work from the browser's address bar, I turned off "html5Mode" in Angular and made links #-based.
kudos to this blog
I think it is a better solution.
His solution is rewriting the request that doesn't fit to any route and doesn't have any extension to the landing page of angular.
Here is the code.
public class Startup
{
public void Configure(IApplicationBuilder app, IApplicationEnvironment environment)
{
// Route all unknown requests to app root
app.Use(async (context, next) =>
{
await next();
// If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
// Rewrite request to use app root
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/app/index.html"; // Put your Angular root page here
await next();
}
});
// Serve wwwroot as root
app.UseFileServer();
// Serve /node_modules as a separate root (for packages that use other npm modules client side)
app.UseFileServer(new FileServerOptions()
{
// Set root of file server
FileProvider = new PhysicalFileProvider(Path.Combine(environment.ApplicationBasePath, "node_modules")),
// Only react to requests that match this path
RequestPath = "/node_modules",
// Don't expose file system
EnableDirectoryBrowsing = false
});
}
}