根据路线切换ng-include的可见性

lui*_*ati 7 javascript angularjs angularjs-routing

我有以下配置:

$routeProvider
.when('/cars', { templateUrl: 'app/cars/index.html', controller: 'CarsCtrl', reloadOnSearch: false })
.when('/bikes', { templateUrl: 'app/bikes/index.html', controller: 'BikesCtrl', reloadOnSearch: false });
Run Code Online (Sandbox Code Playgroud)

在我的根index.html的某个地方有一个:

<a href="#/cars">Cars</a>
<a href="#/bikes">Bikes</a>
<div ng-view></div>
Run Code Online (Sandbox Code Playgroud)

现在,我希望在DOM中同时加载和生成两个视图,并根据路由/ URL显示其中一个.

类似下面的内容(不是实际的工作代码,只是为了给你一个想法).

app.js:

$routeProvider
.when('/cars', { controller: 'CarsCtrl', reloadOnSearch: false })
.when('/bikes', { controller: 'BikesCtrl', reloadOnSearch: false });
Run Code Online (Sandbox Code Playgroud)

root index.html:

<a href="#/cars">Cars</a>
<a href="#/bikes">Bikes</a>
<div ng-include="'app/cars/index.html'" ng-show="carsVisible"></div>
<div ng-include="'app/bikes/index.html'" ng-show="bikesVisible"></div>
Run Code Online (Sandbox Code Playgroud)

更新:我知道ng-view类型可以做到这一点,但差异,如果微妙,存在.我希望每个视图的html生成一次并始终保留在DOM中.

Mar*_*cok 9

我创建了一个RouteCtrl来通过ng-include加载你的所有视图.没有使用ng-view.我内联了模板.模板可以包含自己的ng-controller指令以引入特定的控制器.

<body ng-controller="RouteCtrl">
  <a href="#/cars">Cars</a>
  <a href="#/bikes">Bikes</a>
  <div ng-controller="RouteCtrl">
      <div ng-include="'/cars.html'"  ng-show="carsVisible"></div>
      <div ng-include="'/bikes.html'" ng-show="bikesVisible"></div>
  </div>

  <script type="text/ng-template" id="/cars.html">
     Cars template.
  </script> 
  <script type="text/ng-template" id="/bikes.html">
     Bikes template.
  </script> 
Run Code Online (Sandbox Code Playgroud)

$ routeProvider仍然配置,但没有指定模板或控制器,导致RouteCtrl始终处于活动状态.该控制器侦听$routeChangeSuccess事件并相应地操纵ng-show属性.

app.config(function($routeProvider) {
  $routeProvider
     .when('/cars', {} )
     .when('/bikes', {})
});

app.controller('RouteCtrl', function($scope, $route, $location) {
  $scope.$on('$routeChangeSuccess', function() {
    var path = $location.path();
    console.log(path);
    $scope.carsVisible = false;
    $scope.bikesVisible = false;
    if(path === '/cars') {
       $scope.carsVisible = true;
    } else if(path === '/bikes') {
       $scope.bikesVisible = true;
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

Plunker

这个解决方案的想法来自@Andy.