1

I have been trying to make a angularjs application where I want to route to a different html page on a button click. But is not working for some unknown reasons.

My html code

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
     <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular-route.js"></script>
     <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

<body ng-controller="Controller">
<h1>Plunkr Example</h1>
  <button ng-click="changeview()">ClickMe</button>
  <h1>MainPage</h1>
</body>
</html>

My Code

var app = angular.module("app", ['ngRoute'])

app.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

app.config(['$routeProvider',
  function ($routeProvider) {
      $routeProvider.
        when('/Details', {
            templateUrl: 'details.html'
        }).
        when('/Main', {
             templateUrl: 'main.html'
         }).
        otherwise({
            redirectTo: '/Main'
        });
  }]);

app.controller("Controller", function($scope,$routeParams,$location){
  //$scope.ProductId = $routeParams.id;
  $scope.changeview = function () {
        console.log('in function changeview');
        $location.path('/Details');
    }
})

Here is my plunkr

Please help.

usersam
  • 1,125
  • 4
  • 27
  • 54

2 Answers2

3

You have missed to add the ng-view directive. It needs to be included for the routing to be able to rendered the templates

<div ng-view></div>

Working plunker

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
2

You need to have ng-view directive in index.html

 <div class="viewWrapper">
        <div ng-view></div>
</div>

WORKING DEMO

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thanks a lot. It worked like charm. Dont know how I missed that part. – usersam May 16 '18 at 18:03
  • Just one more doubt. Now the url I can see "http://localhost:3000/#/Main" and "http://localhost:3000/#/Details" on click. Is it possible to remove hash from URL ? I would prefer to have url like "http://localhost:3000/Main" and "http://localhost:3000/Details" . Please suggest something. – usersam May 16 '18 at 18:06
  • @sand [Here is a link for how to make your URL's pretty](https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag) – Tyler May 16 '18 at 18:07
  • I tried , $locationProvider.html5Mode(true); as per the url you suggested but it didn't work. – usersam May 16 '18 at 18:15