0

I'm trying to change the view using $location.

This is how i tried to do this.

View

<body ng-app="myApp" ng-controller="testCtrl">

        <button ng-click="click();">Press</button>

</body>

Controller

var app = angular.module('myApp',[]);

app.controller('testCtrl',function($scope,$location){


   $scope.click = function(){

      $location.path('/main');

   }; 

});

app.js

angular.module('myApp', [
    'ngRoute',
    'myApp.view2',
    'myApp.version'
]).
        config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider, testCtrl) {
                $locationProvider.hashPrefix('!');

                $routeProvider


                        .when('/main',
                                {
                                    templateUrl: '/view2.html',
                                    controller: testCtrl

                                })

                        .otherwise({redirectTo: '/view1'});
            }]);

So when i click the button i can see the url changes from

http://localhost:8383/etest/index.html

to

http://localhost:8383/etest/index.html#/main

How can i fix this?

CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • Does the answer from http://stackoverflow.com/questions/27941876/how-to-redirect-to-another-page-using-angular-js help you? – Kees van Lierop Jan 13 '17 at 09:47
  • There is nothing to fix. This is the expected behavior. But you're using ng-route without any ng-view in your index.html page. So the main view can't display itself anywhere. https://docs.angularjs.org/api/ngRoute – JB Nizet Jan 13 '17 at 09:57
  • try to put this $locationProvider.hashPrefix('!'); ..as JB says it's not a bug ... but if you want to see url different you can use html5 mode .. activate it with $locationProvider.html5Mode(true); – federico scamuzzi Jan 13 '17 at 10:00
  • @JBNizet where should i include ng-view ? – CraZyDroiD Jan 13 '17 at 11:52

1 Answers1

0

You missed out to include ng-view.

<body ng-app="myApp">
<div ng-view></div>
</body>

 // view2.html
<div ng-controller="testCtrl">
        <button ng-click="click();">Press</button>
</div>

 app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider, testCtrl) {
            $locationProvider.hashPrefix('!');
            $routeProvider
                    .when('/main', {
                                templateUrl: 'templates/view2.html',
                                controller: testCtrl
                            })
                    .otherwise({redirectTo: '/view1'});
        }]);

  $scope.click = function(){

  $location.path('/contact'); //you are in main path, So give different path then only you can see the location change easily.
 $route.reload(); // reload the route

};

Manikandan Velayutham
  • 2,228
  • 1
  • 15
  • 22