在AngularJS中为多个部分视图创建单个HTML视图

24
我希望创建一个包含多个
标签的单个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;
}]);

首页文件.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> 

在partials文件夹中,我有两个名为edit.html和productlist.html的HTML视图。

我希望将它们合并成一个单独的HTML文件,并通过路由调用它们(divs)。如何实现这一点?


请解释一下,您是否想要将 div 添加到 index.html 中? - Ivan Dyachenko
不是在index.html文件中,而是在其他的html文件中。 - z22
为什么不使用jQuery?或者只是JavaScript来显示/隐藏div,全部在同一个div中。 - nycynik
3个回答

42

您可以使用ng-switch根据路由参数条件性地渲染包含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'});

而在你的控制器中:

    function productsCtrl($scope, $routeParams) {
      $scope.productId = $routeParams.productId;
    }

在你的HTML中:

    <...productListHtml...>
    <div ng-switch="productId != null">
      <div ng-switch-when="true" ng-include="'partials/product.html'">
    </div>

0

我在Angular中嵌套视图和深链接方面遇到了问题,因为$routerProvide不支持多个ng-view.. 但我找到了一个可能的解决方案,here。它基于手动处理请求上下文和呈现上下文来实现。


0

我曾经遇到过同样的问题,现在有一个解决方案:使用UI-Router

使用这个而不是ngRoute的优点是,您可以使用“ui-view”命名约定在同一页中拥有多个视图。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接