AngularJS无法从控制器路由

AngularJS cannot route from controller

本文关键字:控制器 路由 AngularJS      更新时间:2023-09-26

我使用的是像这样的angularJS路由

$routeProvider.
      when('/wall', {controller:DashboardCtrl, templateUrl:'/chutirghonta_repo/contentpanel/views/dashboard.html'}).
      when('/books', {controller:BooksCtrl, templateUrl:'/chutirghonta_repo/contentpanel/views/books.html'}).
      when('/tests', {controller:TestsCtrl, templateUrl:'/chutirghonta_repo/contentpanel/views/tests.html'}).
      when('/createbook', {controller:CreateBookCtrl, templateUrl:'/chutirghonta_repo/contentpanel/views/bookcreation.html'}).
      when('/createbookpage', {controller:CreateBookPageCtrl, templateUrl:'/chutirghonta_repo/contentpanel/views/bookpagecreation.html'}).
      otherwise({redirectTo:'/wall'});
      ;

现在,在我的一个控制器中,我必须重定向到另一条路线,所以我使用

$scope.add = function(){
    window.location = "/testwebsite/contentpanel/#/createbook";
}

上面的代码不起作用。它让我回到默认路线,即

window.location = "/testwebsite/contentpanel/#/wall";

但是,令人惊讶的是,下面的代码可以工作,并将我引导到所需的页面

$scope.add = function(){
    window.open("/testwebsite/contentpanel/#/createbook");
}

在我的视图层中,我有一个html页面,其中包含以下代码片段

<a href="#" ng-click="add()" class="btn btn-primary">Add New Book</a>

我没有主意了。window.open工作,但window.location不工作

而不是

window.location = "/testwebsite/contentpanel/#/createbook";

使用

$location.url('/createbook')

解决了它。

我更改了

<a href="#" ng-click="add()" class="btn btn-primary">Add New Book</a>

<button ng-click="add()" class="btn btn-primary">Add New Book</button>

此外,正如Arnaud Gueras所提到的,

最好使用

$location.url('/createbook');

而不是

window.location = '/testwebsite/contentpanel/#/createbook';

因为$location.url只指定路径的最后一部分,其中作为window.location指定整个路径(当我的主机更改时可能会更改)