【问题标题】:AngularJS: radio checkbox model doesn't changeAngularJS:单选框模型不会改变
【发布时间】:2016-07-17 00:08:44
【问题描述】:

这是我的代码:

<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"。它再次起作用。

为什么?为什么会这样?

【问题讨论】:

    标签: javascript angularjs radio


    【解决方案1】:

    范围问题


    这是因为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>
    

    如您所见,最好使用object.property,而不是使用$parent

    替代方案


    另外,另一种方法是向控制器添加更新方法。由于 Scope Inheritance,您可以在 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>
    

    【讨论】:

      【解决方案2】:

      在您的代码中为每个单选按钮创建了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 函数的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多