AngularJS中的部分视图

18

我是Angular的新手,希望能得到一些建议。基本上,我有一个一对多的关系——一个类别(Category)有几个产品(Product), 我有一个布局页面,在那里我呈现不同的部分视图:

<div class="mainContent">
     <ng-view></ng-view>
</div>

我的第一个视图显示类别列表,当其中一个被点击时,我展示了第二个视图,它分为两部分:特定类别的产品列表和类别列表,示意图如下:

enter image description here

我的问题是,我不知道如何在产品列表中使用另一个部分,因为我想将它们保留在单独的 .html 文件中。

我配置了路由:

app.config(function($routeProvider, $locationProvider) {
$routeProvider
    .when('/category', {
        templateUrl: 'category.html',
        controller: 'categoryController as catCtrl'
    })
    .when('/category/:id', {
        templateUrl: 'categoryDetail.html',
        controller: 'categoryDetailController as catDetailCtrl'
    })       
    .when('/product/:category_id', {
        templateUrl: 'product.html',
        controller: 'productController as productCtrl'
    })
    .otherwise({
        redirectTo: "/category"
    });
});

还有控制器:

app.controller("categoryController", function($http)
{
    var vm = this;
    vm.categories = somedata;
});
app.controller("categoryDetailController", function($http, $routeParams)
{
   var vm = this;
   vm.category = somedata;//current category from REST api, using $routeParams.id
});
app.controller("productController", function($http, $routeParams)
{
   var vm = this;
   vm.products = somedata;//product list of current category using $routeParams.category_id
});

在我的第一个视图——category.html中,我有一系列类别及其相关的链接:

<a href="#/category/{{category.id}}">

在第个- categoryDetail.html页面上,我再次列出类别,但是链接不同。
<a href="#/product/{{category.id}}">

在最后一个视图 - product.html,我列出了产品。

到目前为止,当我在categoryDetail.html中点击类别时,我的product.html会在布局的mainContent div中呈现,而我需要它作为内部部分呈现在categoryDetail.html中。我试着再次使用<ng-view>,但这似乎不正确。


1
你为什么不使用状态(states)呢?比如angular-ui-router?另外,点赞这张图片。 - Katana24
你考虑过使用ngInclude而不是ngView吗? - Huske
@Katana24,我读到过ui-router适用于大型应用程序,但我的应用程序相当小,但如果我需要对产品列表进行分页,我是否应该使用ui-router? - Gyuzal
1个回答

8

在AngularJS中,有几种可用于实现局部视图的方式。

ng-include

如果没有逻辑或者该逻辑将由父级作用域提供,则可以将HTML文件直接包含到视图中。

示例:

<div ng-include="'/path/to/your/file.html'"></div>

新指令

如果您的局部文件中有一些逻辑,并且希望将其作为应用程序中的单独模块使用,我强烈建议创建一个新指令。

示例。

PS. 如果您是Angular的新手,这里可能会很有用 :-)


在使用 ng-include 的情况下,需要注意单引号周围的双引号。 - Padraic

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