2017-01-13 86 views
0

我试图改变视图使用$位置。

这是我试图做到这一点。

查看

<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 

我怎样才能解决这个问题?

+0

请问来自http://stackoverflow.com/questions/27941876/how-to-redirect-to-another-page-using-angular-js的答案对你有帮助吗? –

+0

没有什么可以解决的。这是预期的行为。但是你在index.html页面中使用ng-route而没有任何ng-view。所以主视图不能在任何地方显示。 https://docs.angularjs.org/api/ngRoute –

+0

尝试把这个$ locationProvider.hashPrefix('!'); ..因为JB说这不是一个bug ...但如果你想看到不同的网址,你可以使用html5模式..激活它$ locationProvider.html5Mode(true); –

回答

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 

};