Ng model not working for switch in AngularJS

I am new to Angular and I am trying to get the value of the switch that the user selected using the ng model. But I do not get any result in the "selected contact".

Here is my HTML

<!doctype html> <html ng-app> <head> <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script> <script src="script.js"></script> </head> <body> <form name="myForm" ng-controller="Ctrl"> <table border="0"> <th>Contact Type</th> <tr ng-repeat="contact in contacttype"><td> <input type="radio" ng-model="contactname" name="group1" value="{{contact.name}}">{{contact.name}} </td> </td></tr></table> <tt>selected contact = {{contactname}}</tt><br/> </form> </body> </html> 

Below is my main.js

  function Ctrl($scope) { $scope.contacttype = [ {name: 'Both' }, {name: 'User'}, {name: 'Admin'} ]; } 

What am I doing wrong here? Failed to find out !!!

+61
javascript angularjs angularjs-scope
Sep 03 '13 at 13:56 on
source share
4 answers

Since ng-repeat creates its own scope, and what you are trying to do is assign the value of the parent scope from the scope of the child. So you can do

 <input type="radio" ng-model="$parent.contactname" name="group1" value="{{contact.name}}"> 
+103
Sep 03 '13 at 14:08
source share

So, I had the same problem, and using $ parent with the ng model did not seem to work. My problem was that I had groups of checkboxes but the same name attribute was used for each of them. He eventually hid the default switch in the last group.

Make sure you use different name attributes for each individual group.

+5
Sep 22 '14 at 22:58
source share

 var app = angular.module('myApp', []); app.controller('formCtrl', function($scope) { $scope.devices = [{ nameD: "Device 1" }, { nameD: "Device 2" }, { nameD: "Device 3" }, { nameD: "Device 4" }]; }); 
 <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="app-controller-r.js"></script> <body> <div ng-app="myApp" ng-controller="formCtrl"> <form> <ul> <li ng-repeat="device in devices"> <label>{{device.nameD}} <input type="radio" ng-model="$parent.deviceType" value="{{device.nameD}}" /> </label> </li> </ul> <button>Submit</button> </form> {{deviceType}} </div> </body> </html> 
+1
May 17 '16 at 3:15
source share

if you use the directive several times and you use for and id tags with tags ... Be sure to use the $id scope reference

 <li ng-repeat='add_type in types'> <input id="addtester_{{ add_type.k }}_{{ $parent.$id }}" type="radio" ng-model="$parent.addType" ng-value='add_type.k' class="tb-form__input--custom" / <label for="addtester_{{ add_type.k }}_{{ $parent.$id }}">{{ add_type.v }}</label> </li> 

Otherwise, you will have directives that share the same inputs and make them appear as if they are not working.

+1
Aug 05 '16 at 18:37
source share



All Articles