AngularJS:单选复选框模型不会改变
AngularJS: radio checkbox model doesn't change
这是我的代码:
<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
函数。
相关文章:
- AngularJS:单选复选框模型不会改变
- 当模型改变时,进度条的最大值不会改变
- 当下拉选择通过模型改变时,如何触发jquery事件
- Ajax响应并没有改变我的视图模型
- 当模型更新时,backbone和knockout如何使视图改变
- 如何在angular2中改变模型的值
- 当视图模型属性改变复选框值时被通知
- 如何改变angularjs的模型,其中的复选框从jquery改变
- 当模型改变时,Javascript /backbone事件
- 当模型在jQuery事件中发生改变时,Angular 2不会刷新视图
- AngularJS在模型因事件而改变后不刷新视图
- 如何改变模型和渲染木偶视图从另一个视图
- v模型上的输入,动态地改变其他脚本的值
- 我怎么知道一个模型是否在Backbone.js中没有被改变?
- 淘汰——改变另一个视图模型值
- Angularjs:当模型改变时,单选按钮检查状态绑定模型值失败
- 更改url后,Angular模型不会改变(更新)
- 当改变模型时,AngularJS视图不更新
- 在Angular中,如何在改变模型后更新视图
- 在Angular中,视图在改变模型时不会更新