为angularjs中的多个局部视图创建单个html视图

z22*_*z22 23 routing routes angularjs

我希望创建一个包含多个标签的单个html文件.这些应该作为单独的单独视图,通常保存在partials文件夹中.然后我希望在路由控制器中指定它们.现在我正在做如下:app.js

    angular.module('productapp', []).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/productapp', {templateUrl: 'partials/productList.html', controller: productsCtrl}).
        when('/productapp/:productId', {templateUrl: 'partials/edit.html', controller: editCtrl}).
        otherwise({redirectTo: '/productapp'});
        }], 
        ['$locationProvider', function($locationProvider) {
            $locationProvider.html5Mode = true;
}]);
Run Code Online (Sandbox Code Playgroud)

的index.html

    <!DOCTYPE html>
<html ng-app = "productapp">
<head>
<title>Search form with AngualrJS</title>
        <script src="../angular-1.0.1.min.js"></script>
        <script src="http://code.jquery.com/jquery.min.js"></script>
        <script src="js/products.js"></script>
        <script src="js/app.js"></script>
</head>
<body>
    <div ng-view></div>
</body>
</html> 
Run Code Online (Sandbox Code Playgroud)

在partials文件夹中:我有2个名为edit.html和productlist.html的html视图

我希望将它们组合成一个独立的文件而不是创建这两个文件,并通过路由调用它们(div).我该怎么做呢?

And*_*lin 42

您可以使用ng-switch有条件地使用include呈现productList,具体取决于路由参数.

在您的配置中尝试此操作:

    angular.module('productapp', [])
      .config(['$routeProvider', function($routeProvider) {
      $routeProvider
        .when('/productapp', {templateUrl: 'partials/productList.html', controller: productsCtrl})
        .when('/productapp/:productId', {templateUrl: 'partials/productList.html', controller: productsCtrl})
        .otherwise({redirectTo: '/productapp'});
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

    function productsCtrl($scope, $routeParams) {
      $scope.productId = $routeParams.productId;
    }
Run Code Online (Sandbox Code Playgroud)

在你的HTML中:

    <...productListHtml...>
    <div ng-switch="productId != null">
      <div ng-switch-when="true" ng-include="'partials/product.html'">
    </div>
Run Code Online (Sandbox Code Playgroud)