[英]ng-model not working for radio button in AngularJS
我是Angular的新手,我正在嘗試獲取用戶使用ng-model選擇的單選按鈕的值。 但我沒有在“選定的聯系人”中獲得任何輸出。
這是我的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>
下面是我的main.js
function Ctrl($scope) {
$scope.contacttype = [
{name: 'Both' },
{name: 'User'},
{name: 'Admin'}
];
}
我在這做錯了什么? 無法搞清楚!!!
因為ng-repeat
創建了自己的范圍,而您嘗試執行的操作是將值從子范圍分配給父范圍。 所以你可以做到
<input type="radio" ng-model="$parent.contactname" name="group1" value="{{contact.name}}">
所以我遇到了同樣的問題,使用帶有ng-model的$ parent似乎沒有起作用。 我的問題是我有一組復選框,但每個復選框使用相同的名稱屬性。 它最終隱藏了最后一組中的默認選中單選按鈕。
確保為每個不同的組使用不同的名稱屬性。
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>
如果您多次使用該指令並且您正在使用for
和id
with labels ...請確保使用對作用域的$id
的引用
<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>
否則,您將獲得共享相同輸入的指令,並使其看起來好像不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.