angular $ location路径更改

时间:2017-01-13 09:44:41

标签: angularjs ngroute

我正在尝试使用$ location更改视图。

这就是我试图这样做的方式。

查看

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

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

</body>

控制器

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'});
            }]);

所以当我点击按钮时,我可以看到网址从

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

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您错过了包含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

};