angularjsangular-ui-routerngrouteroute-providerangularjs-ng-route

ngRoute is not changing view when click of <a> tag


I am new to Angular JS and stuck in an issue...i dont know what is happening.Please help to fix it.

I have index file and app.js is connected ,app is using ngRoute...see code below.

var app = angular.module('routedapp',['ngRoute']);
//app.config("$routeProvider",function($routeProvider)) also tried this

app.config(function($routeProvider) {
$routeProvider.when("/",{
    templateUrl: "views/home.html"
})
.when("/post",{
    templateUrl: "views/post.html"
})
.when("/contact",{
    templateUrl: "views/contact.html",
    controller: "contactCtrl"
})

})
app.controller('contactCtrl', function($scope){
$scope.lalteen = function(){
    console.log("clicked");
}

})

and have 4 pages... index.html , home.html , post.html and contact.html.

//index.html code

<html>
<head>
<title>Routed</title>

</head>
<body ng-app="routedapp" >
<div>welcome</div>
<div>
    <p ng-click="lalteen()">click me</p>
</div>

<!-- views here-->
<div ng-view >
</div>
    <script src="vendor/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.js"></script>
<script src="app.js"></script>
</body>
</html>

initially, when index.html page loaded it shows home.html content in view ,home.html has 3 links to home,post and contact page....when i click any one....it does not change view but keep changing url like:

http://localhost/route/#!/#%2F  //for home <a> tag
http://localhost/route/#!/#contact //for contact <a> tag and other like that.

PS: following is structure of my content in post.html, home.html and contact.html looks like...

<div>This is post page</div>
<p><a href="#/">Home<a/></p><br>
<p><a href="#/post" ng-click="lalteen()">post</a></p><br>
<p><a href="#/contact">contact</a></p><br>

I am new...plz dnt mind my long explanition...thanks


Solution

  • UPDATE

    OK, so I could figure out what you are trying to do and why your routing is not working.

    First revert the change so you will have the link section as per your original format:

    <div>This is post page</div>
    <p><a href="#">Home<a/></p><br>
    <p><a href="#post" ng-click="lalteen()">post</a></p><br>
    <p><a href="#contact">contact</a></p><br>
    

    And then in your script inject the $locationProvider service and set the default route prefix to an empty string.

     app.config(function($routeProvider, $locationProvider) {
       //note that this line does the magic ;)
       $locationProvider.hashPrefix('');
       //normal routing here
       $routeProvider.when("/",{
         templateUrl: "views/home.html"
       })
       .when("/post",{
         templateUrl: "views/post.html"
       })
       .when("/contact",{
         templateUrl: "views/contact.html",
         controller: "contactCtrl"
       })
     })
    

    Created a working plunker for you here.