2

I want to render different html templates (bound to a model) within ng-repeat.

<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>

Now in the last two divs I actually want the inputs to be bound to parameters of concrete sections.

My model looks like this:

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

I could make it an object instead of an array

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

And then easily bind to it

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

But then I can't use filter and ordering on it.

1
  • Perhaps I could dynamically compile the div, but i need a way to make the IF inside the repeater. Commented Jan 21, 2013 at 12:53

1 Answer 1

2

There are many ways of doing this.

  1. You can use ng-show (and/or ng-hide) to act like if's and show only the elements corresponding to each model (child or work). The problem of this approach is that it will just hide the elements from the oposing model and not remove them, which increases the DOM unnecessarily.

    <div class="work" ng-show={{isWork()}}>work template</div>
    <div class="child" ng-show={{isChild()}}>child template</div>
    
  2. Use a directive like Angular-UI ui-if (this will avoid the problem of maintaing unnecessary DOM elements).

    <div class="work" ui-if={{isWork()}}>work template</div>
    <div class="child" ui-if={{isChild()}}>child template</div>
    
  3. Create a custom directive to render your own templates for each model, like in this example fiddle: http://jsfiddle.net/bmleite/kbxJm/

Sign up to request clarification or add additional context in comments.

1 Comment

The last fiddle was exactly what I needed. Thanks you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.