【问题标题】:Partial views in AngularJSAngularJS 中的部分视图
【发布时间】:2016-07-29 10:28:22
【问题描述】:

我是 Angular 新手,如果有任何建议,我将不胜感激。 基本上,我有一对多的关系——一个Category 有几个Product, 我有渲染不同部分视图的布局页面:

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

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

我的问题是我无法弄清楚如何将另一个部分用于产品列表,因为我想将它们保存在单独的 .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,我有带有 href 的类别列表:

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

第二 - categoryDetail.html,我再次列出类别,但有另一个href:

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

最后视图 - product.html 我列出了产品。

到目前为止,当我单击 categoryDetail.html 内的类别时,我的 product.html 会呈现在布局的 mainContent div 中,而不是 - 我需要将其呈现为 categoryDetail.html 内的内部部分。我尝试再次使用&lt;ng-view&gt;,但这似乎不正确。

【问题讨论】:

  • 您不使用状态的任何特殊原因?即角度用户界面路由器?另外 - 图片 +1
  • 你考虑过用 ngInclude 代替 ngView 吗?
  • @Katana24,我听说 ui-router 用于较大的应用程序,我的应用程序很小,但是如果我需要对产品列表进行分页,我应该使用 ui-router 吗?

标签: javascript html angularjs angular-routing


【解决方案1】:

在 AngularJS 中有几种方法可以实现局部化。

ng-include

如果没有逻辑,或者它将从父范围提供,您只需将 html 文件包含到您的视图中。

例子:

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

新指令

如果你的部分有一点逻辑,并且你想在你的应用程序中将它用作一个单独的模块 - 我强烈建议构建一个新指令。

Example.

PS。如果您是 Angular 新手,this 可能会很有用:-)

【讨论】:

  • 在使用ng-include的情况下要注意单引号两边的双引号
猜你喜欢
  • 1970-01-01
  • 2016-05-22
  • 2014-12-08
  • 2014-12-02
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
相关资源
最近更新 更多