【问题标题】:assign alias to long reference names inside ng-repeat为 ng-repeat 中的长引用名称分配别名
【发布时间】:2014-09-17 05:10:33
【问题描述】:

我希望能够为 ng-repeat 指令中的长引用名称分配别名。

现在我有 2 个复杂对象,一个充当另一个的一种分组索引。 ng-repeat 模板代码运行良好,但它变得非常难以阅读,我害怕在几个月后再次使用它。

如果可能,我想转换类似的东西

<div ng-repeat="a in apples">
    <div>
        <span>Type</span>
        <span>{{a.category[1].information.type}}</span>
    </div>
    <div>
        Don't you just love <span>{{a.category[1].information.type}}</span> apples. 
        My granny says {{a.category[1].information.type}} apples are the best kind. 
        I would pick {{a.category[1].information.type}} over {{apples[0].category[1].information.type}} apples any day of the week.
    </div>
</div>

进入这样的事情

<div ng-repeat="a in apples"
     ng-example-assign="ta = a.category[1].information.type">
    <div>
        <span>Type</span>
        <span>{{ta}}</span>
    </div>
    <div>
        Don't you just love <span>{{ta}}</span> apples. 
        My granny says {{ta}} apples are the best kind. 
        I would pick {{ta}} over {{apples[0].category[1].information.type}} apples any day of the week.
    </div>

</div>

我为这个例子编写的ng-example-assign 指令。谁能告诉我这样的事情是否可以使用 angular 或 ng-repeat?可能是我需要重新考虑代码,但我想我会先在这里问。蒂亚!

【问题讨论】:

  • 非常幼稚的实现。 jsfiddle.net/kgc0dL6e.
  • 感谢 javaCity。当我尝试像您所做的那样直接分配它时,我遇到了同样的回声问题。这很好,但不如 ng-init!
  • 确实如此。我知道这不是正确的方式,所以我把它放在 cmets 中:)

标签: javascript angularjs


【解决方案1】:

您可以为此使用 ng-init:

<div ng-controller="MyCtrl">
    <div ng-repeat="s in data" ng-init="address = s.address">
        {{ address }}
     </div>
</div>

jsfiddle: http://jsfiddle.net/5yfgLgr9/2/

【讨论】:

  • 我真的认为 ngInit 非常无用(尤其是用于将数据加载到控制器中),但我现在从文档中看到,这个示例是 ngInit 唯一合适的用法。再次感谢。我的模板看起来已经很多干净了。 docs.angularjs.org/api/ng/directive/ngInit
  • @chriskelly 实际上,我最终使用 nginit 的次数超过了文档推荐的次数。对于一些小事件处理,它可以让你在没有额外 js 的情况下做很多事情——显然它很容易被滥用……所以要小心。
【解决方案2】:

使用具有独立作用域的指令会相当简单。

模板 HTML

<div assign="ta" source="data[0].items[0].subitems[0]">

指令

app.directive('assign',function(){
  return {
    scope:{'assign':'@', "source": '='},
    templateUrl: 'testTemplate',
    link:function(scope){
      scope[scope.assign]=scope.source;
    }
  }
});

通常最好避免使用 ng 命名自定义指令,以避免与升级或可能也使用它们的第三方模块发生冲突

DEMO

【讨论】:

  • 这很有效,而且看起来很灵活。但是,我认为 Daniel 提供的 ng-init 解决方案更简单,所以我会接受。我将避免在指令名称中使用 ng :D。谢谢!
  • 其实我同意ng-init...它从来没有在我的脑海中浮现过,更简单,也没有孤立的范围
猜你喜欢
  • 1970-01-01
  • 2012-06-12
  • 2021-01-04
  • 1970-01-01
  • 2015-02-15
  • 2015-02-17
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多