【问题标题】:AngularJS: load partial view into page dynamicallyAngularJS:将部分视图动态加载到页面中
【发布时间】:2013-05-11 10:46:25
【问题描述】:

创建我的第一个 AngularJS 应用程序。

ng-repeat:er 加载标题。每个标题都是可点击的。单击标题时,ajax 调用会获取更多 JSON 数据。我需要在点击的标题下方添加这些数据。

通常,我会将 HTML 创建为字符串并将其附加到源代码中。但是由于我使用的是 AngularJS,所以应该有一种方法可以创建带有 HTML 和另一个 ng-repeat 的局部视图。

如何做到这一点?

【问题讨论】:

  • 这听起来很适合在您的页面中实现路由。看看 Angular 官方教程的这一部分:docs.angularjs.org/tutorial/step_07 和这个文档条目:docs.angularjs.org/api/ng.directive:ngView
  • 是的,这似乎是最好的方法。我首先考虑不使用路线,但这会做。我不明白的一件事是:你如何将一个局部视图“附加”到另一个局部视图中?
  • 看看ng-include指令:docs.angularjs.org/api/ng.directive:ngInclude。有了它,您可以包含也可以在其中包含 ng-include 的部分——在部分中包含部分等等。您可以动态更改部分的源(通过将 url 设置为某个对象引用而不是字符串字面量 - 它显示在我包含的文档条目的示例中)。
  • 也许在指令中有视图,然后在需要时将指令的 html 作为元素附加。也就是说,如果您真的不想预加载 html 并使用 ng-show/ng-hide。

标签: angularjs partial-views


【解决方案1】:

我会按照@Nicolas 的建议使用指令。将此与@Andrew 建议的内容结合起来,您可以做这样的事情。

控制器:

.controller('MainCtrl', function ($scope, $http) {
    $scope.items = [
        {id: 'a', subItems: []},
        {id: 'b', subItems: []}
    ];

    $scope.getSubItems = function(id) {
        $http.get('/sub-items/' + id)
            .then(function() {
                $scope.items.subItems = $scope.items.subItems.push(response.data);
            });
    }
});

查看:

<div ng-repeat="item in items">
  <a ng-click="getSubItems(item)">{{item.id}}</a>
  <list sub-items="item.subItems"></list>
</div>

指令:

.directive('list', function() {
    return {
        restrict: 'E',
        scope: {
          subItems: '=subItems'
        },
        template: '<ul>' +
            '<li ng-repeat="subItem in subItems">{{subItem.id}}</li>' +
          '</ul>'
    };
});

【讨论】:

    【解决方案2】:

    这是一个小例子:您的 JSON 结构简单,每个项目的 json 对象中都有 subItems 数组。

    JS:

    function MyCtrl($scope, $http) {
      $scope.items = [ {id: 'a', subItems: []}, {id: 'b', subItems: []} ];
    
      $scope.getSubItems = function(item) {
        $http.get('/sub-items/' + item.id).then(function(response) {
          //Append the response to the current list of subitems 
          //(incase some exist already)
          item.subItems = item.subItems.concat(repsonse.data);
        });
      };
    }
    

    HTML:

    <div ng-repeat="item in items">
    
      <a ng-click="getSubItems(item)">{{item.id}}</div>
      <div ng-show="item.subItems.length">
        <h4>SubItems:</h4>
        <ul>
          <li ng-repeat="subItem in item.subItems">{{subItem}}</li>
        </ul>
      </div>
    
    </div>
    

    【讨论】:

    • 谢谢,这似乎是一个很好的解决方案,但我更喜欢使用局部视图来减少生成的 HTML 的数量,同时在应用程序中也有更好的结构。不过,这可能会在其他时候派上用场。
    • 我会使用指令来做到这一点。
    猜你喜欢
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2015-10-27
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多