HTML部分
<div ng-app> <div ng-controller="CustomCtrl"> <label ng-repeat="user in users"> <input type="radio" name="radio" ng-model="radio" value="{{user.name}}" /> {{user.name}} </label> <br/> {{radio}} <br/> <a href="javascript:void(0)" ng-click="saveTemplate()">Save</a> </div> </div>
角部
function CustomCtrl($scope) { $scope.radio = "John"; $scope.users = [ {"name" : "John","Year" : 18},{"name" : "Tony","Year" : 19} ]; $scope.saveTemplate = function() { console.log($scope.radio); }; }
你可以在这里看到例子 – http://jsfiddle.net/hgf37bo0/2/
解决方法
$scope.radio = { name: 'John' }
然后从html访问它,如下所示:
<input type="radio" name="radio" ng-model="radio.name" value="{{user.name}}" />
您可以在answer中了解为什么这是必要的
来自angularjs docs:
Scope inheritance is normally straightforward,and you often don’t even need to kNow it is happening… until you try 2-way data binding (i.e.,form elements,ng-model) to a primitive (e.g.,number,string,boolean) defined on the parent scope from inside the child scope. It doesn’t work the way most people expect it should work. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.
…
Having a ‘.’ in your models will ensure that prototypal inheritance is in play. So,use
<input type="text" ng-model="someObj.prop1">
rather than
<input type="text" ng-model="prop1">
If you really want/need to use a primitive,there are two workarounds:
Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its own property. Define a function on the parent scope,and call it from the child,passing the primitive value up to the parent (not always possible)