Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Dynamic inputs with unique ngModel inside ngRepeat

I have an element ".form-control" that repeats N times using ngRepeat with custom filter. Inside each ".form-control", there is an input with ngModel "number".

My question is "How can I access "number" parameter of each specific input?"

Here is the code itself:

<p data-height="229" data-theme-id="13423" data-slug-hash="NxEBgb" data-default-tab="html" data-user="docode" class='codepen'>See the Pen <a href='http://codepen.io/docode/pen/NxEBgb/'>NxEBgb</a> by .do {code} (<a href='http://codepen.io/docode'>@docode</a>) on <a href='http://codepen.io'>CodePen</a>.</p> <script async src="//assets.codepen.io/assets/embed/ei.js"></script>

You can see Pen here: http://codepen.io/docode/pen/NxEBgb

In case I ask a wrong question. What I trying to do is a flexbox playground&generator such us http://the-echoplex.net/flexyboxes/ . Each flex item has its own individual form group. Quantity of such form groups depends on the quantity of flex items. So, I need some way to generate these form groups with unique ngModels inside

2 Answers

It's because of the funky stuff going on with Angular's ng-repeat directive and child scopes being created.

See the article Understanding Scopes on the Angular wiki.

Basically, changing a primitive value (string, number, etc) with ng-model within ng-repeat with create a new child scope that makes a copy of the current value from the parent scope. You'd need to change them to use a property of an object instead if you want to change the parent scope.

In any case, if all you want is the position of the particular item in the list/collection generated by ng-repeat, you can use $index:

<div class="wrapper" ng-app='app' ng-controller="AppController">
    <div class="form-control" ng-repeat="n in [] | range:number">
        <input type="text" ng-model="newVar">
        <span>{{$index}}</span>
    </div><!-- //form controll -->
    <input type="range"  ng-model="number" max="9">
    <label>Repeat input fields {{number}} times</label>
</div>

Hello Iain!

Thank you for your reply and provided article! I really appreciate your help!