Sweetie
Sweetie

Reputation: 1368

Starting with single page apps

I am a beginner in Angularjs and I have downloaded the template "Angular Start" for angularjs. It has come with some inbuilt files . Like homecontroller, AppjsFolder etc.

I wonder how I can start with the angularproject if I am with an empty Mvc Project? Moreover When I run the application, I am defaulted with this url in the browser: "http:/somelocalAddress/#/home" . Can anybody tell me how # is attached with the url as I can see the route.config file it does not have any.

I know there are some anchor tags in Layout.cshtml

 <li data-ng-class="{active : activeViewPath==='/home'}"><a href='#/home'>Home</a></li>
                    <li data-ng-class="{active : activeViewPath==='/demo'}"><a href="#/demo">Demo</a></li>
                    <li data-ng-class="{active : activeViewPath==='/angular'}"><a href='#/angular'>Learn Angular</a></li>
                    <li data-ng-class="{active : activeViewPath==='/about'}"><a href='#/about'>About</a></li>
                    <li data-ng-class="{active : activeViewPath==='/contact'}"><a href='#/contact'>Contact</a></li>

Here , the href of anchortags are attached with # and it makes a point that url gets # on clicking the anchor tag but when I run the application why there is /#/Home

Please guide me.

Upvotes: 2

Views: 299

Answers (1)

cgcladera
cgcladera

Reputation: 286

You are using Angular ngRoute module. Which is a full-ajax navigation controller. That means when you navigate through routes you are not actually going any where, ngRoute downloads partials htmls and renders them inside the div tagged with ng-view attribute creating a "fake" (but high-performance) navigation experience.

Angular uses # in order to avoid browsers load whole page every route change action. That's why the anchor in your code is using # as well.

Your code seems to be an extract of a menu, probably a bootstrap menu, and it wants to add 'active' class to the corresponding li section depending on the current path. The controller is probably using $location service in order to find out which is the current path using $location.path() method. When you call path() it returns the current path without '#' thus it isn't using it either in ng-class attribute.

By the way, you might activate $locationProvider's html5mode and do not use prefix # and simply your life ;). It uses the same technology, the problem is your audience will need to use a modern browser, but I'm pretty sure you use other dependencies that require so too, do you?

How to configure html5mode

angular.module('myApp',[
    ...
    'ngRoute'
    ...
])
    .config(function($routeProvider, $locationProvider){
        $routeProvider
             .when('/path/to/my/route')
             .otherwise({
                 redirectTo: '/'
             });
        
        $locationProvider.html5Mode(true);
    });

Upvotes: 4

Related Questions