AngularJS:单选复选框模型不会改变

AngularJS: radio checkbox model doesn't change

本文关键字:改变 模型 复选框 单选 AngularJS      更新时间:2023-09-26

这是我的代码:

<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是父对象,valueselectedInterval的属性。这就是为什么不需要调用change函数。