这是我的代码:
<div ng-controller="TestController">
<input ng-change="change()" ng-repeat="item in array" ng-model="selected" name="group" value="{{item.interval}}" type="radio">{{item.desc}}</input>
</div>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('TestController', function ($scope) {
$scope.array = [ {
interval: "1"
}, {
interval: "3"
}, {
interval: "24"
}];
$scope.selected = 1
$scope.change = function () {
console.log($scope.selected);
}
});
</script>
当我单击不同的单选复选框时,$scope.selected
值根本没有变化,仍然1
.
但是当我将$scope.selected
点更改为对象时:
$scope.selected = {
value: 1
};
并将输入标记的模型绑定到 value 属性:ng-model="selected.value"
。它再次工作。
为什么?为什么会这样?
范围问题
这是因为ng-repeat
创建了自己的范围。因此selected
现在是ng-repeat范围的新属性。如果你绝对需要,你可以这样做:
<div ng-controller="TestController"> //parent scope
//ng-repeat create it's own scope here, so you must reference the $parent to get the selected value.
<input ng-change="change()" ng-repeat="item in array" ng-model="$parent.selected" name="group" value="{{item.interval}}" type="radio">{{item.desc}}</input> //
</div>
与其使用$parent
不如使用您发现的object.property
。
另类
此外,另一种方法是向控制器添加更新方法。由于作用域继承,您可以在 ng-repeat 中访问父方法并更新父作用域selected
属性:
//Add to your controller
$scope.updateSelected= function (selected) {
$scope.selected = selected;
}
//new HTML
<div ng-controller="TestController">
<input ng-change="updateSelected(selected)" ng-repeat="item in array" ng-model="selected" name="group" value="{{item.interval}}" type="radio">{{item.desc}}</input> //
</div>
在您的代码中为每个单选按钮创建separate scope
因此在选择另一个单选按钮时没有影响。 因此,您应该为每个单选按钮使用parent object
,并为此parent object property
值将影响每个更改。
喜欢:在您的控制器中:
$scope.selectedInterval= {value: 1};
在 HTML 中:
<input ng-repeat="item in array" ng-model="selectedInterval.value" name="group" value="{{item.interval}}" type="radio">{{item.desc}}</input>
这里selectedInterval
是父对象,value
是selectedInterval
的属性。这就是为什么不需要调用change
函数。