javascript - 如何在同一页面上重用 AngularJS 模板

标签 javascript angularjs

我正在尝试设置我的第一个(正确的)SPA AngularJS 应用程序,该应用程序将有几个数据表来过滤两个不同联赛的结果。目前,我可以显示联赛 A 和联赛 B 的两个表格,但它们显示两个联赛的所有结果,因为它们使用相同的模板。

我的模板页面包含一个带有以下 ng-repeat 标记的表格:

<tr ng-repeat="fixtures in items | filter:{ FixtureLeague: 'League A'}" id="fixtures_{{fixtures.Id}}">

这是从主页中的 ng-view div 调用的。我开始考虑使用指令来指定/将数据传递到模板中,但我不确定如何实际完成这项工作。

//Directive - Fixtures
FixturesApp.directive('cFixture', function () {
    return {
        template: '<tr ng-repeat="fixtures in items | filter: { FixtureLeague : "League A"}" id="fixtures_{{fixtures.Id}}">',
        replace: true,
        transclude: true,
        restrict: 'E',
        scope: {
            tree: '=ngModel'
        }
    };
});

是否有任何示例说明如何重用模板并向其传递不同的参数或关于如何实现此目的的建议?

最佳答案

为您的指令添加一个值:

<c-fixture league='League A' ng-Model="..."></c-fixture>

FixturesApp.directive(`cFixture`, function(){
    return {
        template: [
                    '<tr ng-repeat="fixtures in items" | filter: { FixtureLeague: league}',
                    'id="fixtures_{{fixtures.Id}} >"'
                  ].join(' '),

        replace: true,
        scope: {
            league: '@',
            items: '=ngModel'
        },
        restrict: 'E'
    }
})

您的指令有问题:您正在创建一个隔离范围 scope: {...} ,将 ngModel 的值复制到其中到一个名为 tree 的属性。无论如何,您没有将 items 的值传递到任何地方。 ,所以你的 ngRepeat 将不起作用。我在实现中假设您希望将项目集合传递为 ngModel 。否则解释一下,我会纠正它。

就不同联赛而言,我将联赛作为 league 的字符串参数传递给过滤器。属性。 league属性作为字符串 league: @ 插入到范围中.

无论如何,我不会使用过滤器来显示两个不同的联赛集合,而是在模型上创建两个不同的数组,因为过滤器需要遍历所有表格的所有联赛,而且看起来效率不高。

关于javascript - 如何在同一页面上重用 AngularJS 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24054430/

相关文章:

javascript - html5 拖动更改拖动图像或图标

javascript - AngularJs指令嵌入错误和@绑定(bind)

javascript - Angular 下拉指令

html - 搜索栏标题

javascript - 停止带有 promise 的 $interval 函数

javascript - 解析嵌套的 javascript 数组

javascript - 如何动态定位焦点输入

angularjs - 在 iPad Air 中使用 appium 进行测试时, Protractor 脚本无法启动

javascript - 查找图像 ID 并替换为单击的按钮类

javascript - 显示/隐藏选项卡箭头以在溢出时导航其他选项卡