【问题标题】:angularjs custom view for each model每个模型的angularjs自定义视图
【发布时间】:2013-01-21 22:13:36
【问题描述】:

我想在 ng-repeat 中呈现不同的 html 模板(绑定到模型)。

<div ng-repeat="section in sections | filter:unansweredSections">

    // Here i want something like
    if section == children
        render div#children
    else if section == work
        render div#work

</div>


<div style="display:none" id="children">
    // i want to bind this to sections info
    <input ng-model="???.totalChildren" />
</div>


<div style="display:none" id="work">
    // i want to bind this to sections info
    <input ng-model="???.work1" />
    <input ng-model="???.work2" />
</div>

现在在最后两个 div 中,我实际上希望将输入绑定到具体部分的参数。

我的模型如下所示:

$scope.sections = [
    {"name" : "children","totalChildren" : 0},
    {"name" : "work","work1" : "","work2" : ""}
]

我可以把它变成一个对象而不是一个数组

$scope.sections = {
    "children"  : {"totalChildren" : 0},
    "work"      : {"work1" : "","work2" : ""}
}

然后轻松绑定到它

<div style="display:none" id="children">
    <input ng-model="sections.childern.totalChildren" />
</div>

但是我不能对它使用过滤器和排序。

【问题讨论】:

  • 也许我可以动态编译 div,但我需要一种方法在转发器中制作 IF。

标签: angularjs


【解决方案1】:

有很多方法可以做到这一点。

  1. 您可以使用ng-show(和/或ng-hide)来表现得像if's,并且只显示与每个模型(子模型或工作模型)对应的元素。这种方法的问题在于,它只会对反对模型隐藏元素而不删除它们,这会不必要地增加 DOM。

    <div class="work" ng-show={{isWork()}}>work template</div>
    <div class="child" ng-show={{isChild()}}>child template</div>
    
  2. 使用Angular-UI ui-if 之类的指令(这样可以避免维护不必要的 DOM 元素的问题)。

    <div class="work" ui-if={{isWork()}}>work template</div>
    <div class="child" ui-if={{isChild()}}>child template</div>
    
  3. 创建一个自定义指令来为每个模型呈现您自己的模板,就像在这个小提琴示例中一样:http://jsfiddle.net/bmleite/kbxJm/

【讨论】:

  • 最后的小提琴正是我所需要的。非常感谢。
猜你喜欢
  • 2012-03-13
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多