单击单选按钮时如何更新$ scope.animal?
http://plnkr.co/edit/5ikIYfXQw4GyjRKScD7x?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.animals = {
dog: {
label: "Dog"
},
cat: {
label: "Cat"
},
bird: {
label: 'Bird'
}
};
$scope.animal = 'dog';
});
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="(key, val) in animals">
<label>
{{val.label}}
<input type="radio" name="animal" value="{{key}}" ng-model="animal">
</label>
</li>
</ul>
<p>Animal: {{animal}}</p>
</body>
</html>
当您单击单选按钮时,它应该显示您刚刚单击的动物的名称。
答案 0 :(得分:4)
由于ngRepeat
创建了不同的范围,您可以使用$parent
<input type="radio" name="animal" value="{{key}}" ng-model="$parent.animal">
或使用对象:
<input type="radio" name="animal" value="{{key}}" ng-model="animal.name">
$scope.animal = {
name : "dog"
};