每个模型的 angularjs 自定义 View

标签 angularjs

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

<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 中,我实际上希望将输入绑定(bind)到具体部分的参数。

我的模型如下所示:

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

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

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

然后轻松绑定(bind)到它

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

但是我无法对其使用过滤器和排序。

最佳答案

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

  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. 创建一个自定义指令来为每个模型呈现您自己的模板,如本示例中的 fiddle : http://jsfiddle.net/bmleite/kbxJm/

关于每个模型的 angularjs 自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14437121/

相关文章:

javascript - 在 ionic 2 应用程序中打开 PDF 文件

javascript - 在 spring mvc 中通过 AngularJs 提交表单

ruby-on-rails - AngularJS 不发送-X XSRF-TOKEN

javascript - 在 Angular 应用程序中解析 Content-Range header 时出现问题(返回 null)

javascript - 从 ng-repeat 中删除对象

javascript - 如何使用angular js从动态生成的表及其行中计算值?

javascript - 无法在 gmap-window 中设置未定义的属性 'opacity'

angularjs - 如何在 Angular Material 的 md-autocomplete 组件中禁止自由文本?

javascript - 如何从子指令的链接函数调用父指令的链接函数

javascript - 模块化 AngularJS 应用程序 commonJS 与 AMD 模块语法