Adam
Adam

Reputation: 1754

Angular JS: Binding using ng-model with an ng-repeat on a select element

So, I have the following working code:

Angular:

$scope.audit = {user: ''};

HTML:

<md-select ng-model="audit.user"">
    <md-option ng-repeat="u in users" value="{{u.username}}">
        {{u.username}}
    </md-option>
</md-select>

But, previously I was trying to bind as follows.

Angular:

$scope.auditUser = '';

HTML:

<md-select ng-model="auditUser">
    ..
</md-select>

I read a bit online about not binding to primitives within ng-repeat but nothing conclusive. So I was wondering why the latter solution does not work and why do we have to bind our model to objects when using ng-repeat, is it something to do with the $scope and $digest cycles (of which I don't know in much detail)?

Thanks

Upvotes: 1

Views: 95

Answers (1)

Tevin
Tevin

Reputation: 1404

Angular creates a new scope for each object in the ng-repeat directive. If that object is actually a primitive, it is passed by value rather than by reference. Therefore, any changes made in that child scope won't be propagated back to the original object in the parent scope.

Upvotes: 1

Related Questions