AngularJs: binding ng model to switch list

I am trying to associate the selected value in the switch list with ng-model

I have:

 <!DOCTYPE html> <html ng-app="testApp"> <head> <script src="./bower_components/angular/angular.min.js"></script> <script src="test.js"></script> </head> <body ng-controller="testController"> <form> <div ng-repeat="option in occurrenceOptions"> <input type="radio" name="occurrence" ng-value="option" ng-model="selectedOccurrence" /><label>{{ option }}</label> </div> </form> <div>The selected value is : {{ selectedOccurrence }}</div> <!-- This works --> <input type="radio" ng-model="selected2" ng-value="'1'"> 1 <input type="radio" ng-model="selected2" ng-value="'2'"> 2 <input type="radio" ng-model="selected2" ng-value="'3'"> 3 <div>This selected value is : {{ selected2 }} </div> </body> </html> 

For my controller:

 (function () { var app = angular.module('testApp', []); app.controller('testController', function($scope) { $scope.occurrenceOptions = []; $scope.occurrenceOptions.push('previous'); $scope.occurrenceOptions.push('current'); $scope.occurrenceOptions.push('next'); $scope.selected2; }); }()); 

In the first section, I tried to ng-repeat all occurrenceOptions and bind them all to the same model. However, every time I select something, the value of selectedOccurrence does not change.

See plunkr: https://plnkr.co/edit/k1pMgkLdrMUG1blktQx1?p=preview

without ng-repeat and just by typing all the switches, I can make this work. Why is the ng-repeat version not working?

+5
source share
1 answer

The reason for this does not work, you use ng-repeat , and you define the ng-model variable in it. The ng-repeat method works, it creates a new child region (prototypically inherited) at each iteration of the collection. Thus, the ng-model , which is in the ng-repeat pattern, belongs to the newly created area. Here ng-model="selectedOccurrence" create the scope selectedOccurrence variable on each ng-repeat iteration.

To overcome this problem, you need to follow the dot rule when defining a model in AngularJS

Markup

 <body ng-controller="testController"> <form> <div ng-repeat="option in occurrenceOptions track by $index"> <input type="radio" name="occurrences" ng-value="option" ng-model="model.selectedOccurrence" /> <label>{{ option }}</label> </div> </form> <div>The selected value is : {{ model.selectedOccurrence }}</div> </body> 

code

 $scope.model = {}; //defined a model object $scope.model.selectedOccurrence = 'current'; //and defined property in it 

Demo plunkr


OR Another preferred way would be to use the controllerAs template when declaring the controller (use this instead of the $scope internal controller).

HTML

 <body ng-controller="testController as vm"> <form> <div ng-repeat="option in vm.occurrenceOptions"> <input type="radio" name="occurrence" ng-value="option" ng-model="vm.selectedOccurrence" /><label>{{ option }}</label> </div> </form> </body> 

Controller as a demonstration

+13
source

All Articles