angularjs每个模型的自定义视图

时间:2013-01-21 10:58:25

标签: angularjs

我想在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>

但是我不能在其上使用过滤器和排序。

1 个答案:

答案 0 :(得分:2)

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

  1. 您可以使用ng-show(和/或ng-hide)来表现if,并仅显示与每个模型(儿童或工作)相对应的元素。这种方法的问题在于它只会隐藏选择模型中的元素而不会删除它们,这会不必要地增加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/