【问题标题】:How to use "ng-repeat" within template of a directive in Angular JS?如何在 Angular JS 的指令模板中使用“ng-repeat”?
【发布时间】:2013-05-14 20:08:24
【问题描述】:

我是 Angular JS 的新手,我正在尝试创建一个自定义指令,如下所示:

<div linkedlist listcolumns="{{cashAccountsColumns}}"></div>

公司。 控制器将是:

$scope.cashAccountsColumns = [
  {"field": "description", "title": "Description"},
  {"field": "owner", "title":"Owner"},
  {"field": "currentBalance", "title":"Current Balance" }
];

而指令代码是:

return {
      restrict : 'EA',
      transclude : false,
      templateUrl : 'html/linkedlist.html',
      scope: {
         listcolumns: "@"
      },
      link : function(scope, element, attrs) {
      }
}

模板是:

<table class="box-table" width="100%">
  <thead>
    <tr>
      <th scope="col" ng-repeat="column in listcolumns">
        {{column.title}}
      </th>
    </tr>
  </thead>
</table>

但这不起作用。我没有在屏幕上获取 column.title 的值,而是将下面的太多行添加到 DOM:

<th ng-repeat="column in listcolumns" scope="col" class="ng-scope ng-binding"></th>

【问题讨论】:

  • 如果您发现@Ajay beniwal 的答案有用,为什么不将其标记为答案?
  • 原始发帖人看起来好像自从发帖后就没有回来了。

标签: angularjs angularjs-directive angularjs-ng-repeat


【解决方案1】:

@AjayBeniwal 的回答是正确的,但我觉得它可以使用一些额外的解释。

正如Angular documentation 指出的那样(在“隔离指令的范围”部分),scope 选项是一个对象,其中包含每个隔离范围绑定的属性。我们用它来分离(隔离)指令内部的作用域和外部的作用域,然后将外部作用域映射到指令的内部作用域。

scope 对象的每个属性的名称对应于指令 isolate scope 属性。在问题的示例中,scope 对象的唯一属性是 listcolumns。因此,创建指令的 html 上也必须有相应的属性:

<div linkedlist listcolumns="cashAccountsColumns"></div>

scope 属性的名称和指令的属性不需要具有相同的名称。我们可以像这样映射这两个值:

<div linkedlist short-name="cashAccountsColumns"></div>

-

controller: function ($scope) {
    $scope.cashAccountsColumns = 'value';
},
scope: {
     moreDescriptiveName: "=shortName"
},

对于属性名称与您要在指令范围内绑定的值相同的情况,您可以使用以下简写语法:

<div linkedlist my-name="cashAccountsColumns"></div>

-

controller: function ($scope) {
    $scope.cashAccountsColumns = 'value';
},
scope: {
     myName: "="
},


此外,在此示例中,指令属性的值必须对应于指令外部范围的属性。这是因为=shortName 中的= 使用了从外部作用域到隔离作用域的属性的双向绑定,强制将指令的属性值作为表达式求值。正如this answer 雄辩地指​​出的那样,如果我们想要传递一个文字字符串,我们可以使用@ 代替=,或者用双引号和单引号将指令的隔离范围属性括起来:

scope: {
     moreDescriptiveName: "@"
},

或

<div linkedlist short-name="'cashAccountsColumns'"></div>

【讨论】:

    【解决方案2】:

    使用属性传递整个对象将不起作用,您必须使用双向绑定。只需将绑定从 @ 更改为 = 并修改下面的 HTML 以使其工作:

    对指令代码的更改:

    // ...
    scope: {
        listcolumns: "="
    },
    // ...
    

    更改为模板:

      <div linkedlist listcolumns="cashAccountsColumns"></div>
    

    【讨论】:

    • 感谢@Ajay 节省了一天!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多