himanshu
himanshu

Reputation: 208

Single select Check box inside nested ng-repeat

Please take a glance to the demo plunkers for details.

Demo Plunker

Example1

The html of Example1 looks something like this

<tr ng-repeat="class in Classes">
            <td>{{class.name}}</td>
            <td>
              <span ng-repeat="subject in Subjects ">
                <input type="checkbox" name="{{subject.name}}" ng-model="subject.model" 
                ng-change="Print(subject)">{{subject.name}}
              </span>
            </td>
          </tr>

In the above plunker when any one check box is clicked why all are selected ?

Demo Plunker

Example2

The HTML of Example2 likks like

<tr ng-repeat="class in Classes">
        <td>{{class.name}}</td>
        <td>
          <span ng-repeat="subject in Subjects ">
            <input type="checkbox" ng-model="Subject" 
            ng-change="Print(subject,class)">{{subject.name}}
          </span>
        </td>
      </tr>

In the above plunker when any one check box is clicked only one is selected ?

The difference between Example1 and Example2 is ng-model . In Example1 default value which is in $scope is assigned to ng-model but in Example2 new variable is assigned which is not is $scope. I know that If ng-model property doesn't already exist on the scope, it will be created implicitly and added to the scope.

Why single check box selection is possible in Example2 and why not in Example1 ?

Upvotes: 0

Views: 632

Answers (1)

Vivz
Vivz

Reputation: 6630

The reason is because of JavaScript Prototypal Inheritance.

"Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope. It doesn't work the way most people expect it should work. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works. "

Since you are using a primitive for your second scenario, all your ng-model child scope will create its own property that hides/shadows the parent property of the same name.

And in your first scenario, where an object is being used, the above behaviour won't be seen since each ng-model child scope is binded directlty to the parent scope.(each child instance of ng-repeat).

Suppose there was a third scenario where you had made the second ng-model="Subject.modal" and declared $scope.Subject={} in your controller, now checking one checkbox will check all because the value is directly binded to the parent's scope irrespective of the child scope of ng-repeat.

For more details: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Upvotes: 1

Related Questions