This question already has an answer here:
Could someone explain to me why I can't get the current selected radio-button in this simple example. I'm trying to generate dynamically the radio-buttons with an ng-repeat directive and get the current radio-button selected using ng-model. Like this:
Template:
<div ng-repeat="kind in movieKinds">
<input type="radio" name="movies" ng-value="kind" ng-model="kindSelected"> {{kind.name}}<br>
</div>
Selected Movie :{{kindSelected}}
Controller:
mymodule.controller('MainCtrl', [ '$scope',function ($scope) {
$scope.movieKinds = [
{'name' : 'Action', 'movies' : ['Action#1', 'Action#2', 'Action#3']},
{'name' : 'Comedy', 'movies' : ['Comedy#1', 'Comedy#2', 'Comedy#3']},
{'name' : 'Drama', 'movies' : ['Drama#1', 'Drama#2']},
{'name' : 'Horror', 'movies' : ['Horror#1']}
];
}]);
Because
ng-repeat
does create a new child scope(prototypically inherited) on each iteration when it repeats a template on whereverng-repeat
directive has been placed.Here in your case you had
ng-model="kindSelected"
variable insideng-repeat
so that scope variable got create inside theng-repeat
scope and doesn't available outsideng-repeat
directive.To fix such a problem you could use
object
while definingng-model
so that you could followDot rule
while definingng-model
. That means you could define a object called as$scope.model
inside controller & then addkindSelected
property so that the value will get updated on selection of checkbox.Markup
Code
The other way to fix this problem is to use
controllerAs
syntax which will use alias of controller so the scope hierarchy related problem doesn't happen on HTML. Whichever controller variable you want you could use that alias of the controller.