AngularJS:将局部 View 动态加载到页面中

标签 angularjs partial-views

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

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

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

如何才能做到这一点?

最佳答案

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

Controller :

.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>'
    };
});

关于AngularJS:将局部 View 动态加载到页面中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16589172/

相关文章:

javascript - 如何在服务器端过滤提供的 ui-grid 列中为过滤器创建多重选择?

javascript - 如何通过Angular JS取出对象列表

asp.net-mvc - 如何在 asp.net mvc 3 中呈现部分 View ?

javascript - 将 JavaScript 放在分部 View 中是否可以

javascript - 以编程方式刷新所有客户端浏览器中的局部 View

ruby - 部分轨道但被多个 View 使用

angularjs - 如何通过属性指令更改元素的范围?

javascript - AngularJS - 转换 EPOC 日期

javascript - 使用 promise 的 $scope 问题

html - 在多个局部 View 中使用单个共享元素