user2944669
user2944669

Reputation: 165

AngularJS : How to access scopes created by ng-repeat?

I have the following:

<ul>
    <li class="faders" ng-repeat="f in faderlist | faderFilter:from:to">
        <br/><button ng-click="record(f)">Record new setting</button>
        <input ng-model="myname" type="text">
    </li>
</ul>

In the record function, I want to: 1) Access myname 2) Reset myname to some value.

For 1), I can easily get it by passing ng-click="record(f,myname)

But for 2), I'm really annoyed. The ng-repeat do create "inner scopes". How can I access those ? I have try to pass $scope to record but it's not working...

Any ideas ?

Upvotes: 0

Views: 359

Answers (2)

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

you shouldn't care about ng-repat inner scopes except for appending $parent to your function calls something like

<ul>
    <li class="faders" ng-repeat="f in faderlist">
        <br/><button ng-click="$parent.record(f)">Record new setting</button>
        <input ng-model="myname" type="text">
    </li>
</ul>

this asumes that your controllers scope has a function called record wich is not called with the element f of your collection. the only thing you care about ng-repeact inner scopes are the index related variables. the rest should be handled buy the item element and the parent scope.

Upvotes: 0

package
package

Reputation: 4801

Inner ng-repeat scope creates property myname. You cannot pass this property by reference to outer scope. But you can wrap this property with an object and pass it instead. It would make sense to define this property on f, e.g.:

<ul>
    <li class="faders" ng-repeat="f in faderlist | faderFilter:from:to">
        <br/><button ng-click="record(f)">Record new setting</button>
        <input ng-model="f.myname" type="text">
    </li>
</ul>

$scope.record = function(f) {
  f.myname = "newValue";
}

This allows you to modify myname for all faderlist objects in outer scope and inner scope values will update themselves automatically. If you do not want to modify existing f object, you can create a new one:

<ul>
    <li class="faders" ng-repeat="f in faderlist | faderFilter:from:to">
        <br/><button ng-click="record(f, wrapper)">Record new setting</button>
        <input ng-model="wrapper.myname" type="text">
    </li>
</ul>

$scope.record = function(f, wrapper) {
  wrapper.myname = "newValue";
}

Upvotes: 4

Related Questions