Issue
Here is my code:
<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>
When I click different radio checkbox, the $scope.selected
value doesn't change at all, still 1
.
But when I change the $scope.selected
point to an object:
$scope.selected = {
value: 1
};
and bind the input tag's model to the value property: ng-model="selected.value"
. It work again.
Why? Why this happened?
Solution
Scope Issue
It's because ng-repeat
creates it's own scope. So selected
is now a new property of ng-repeat's scope. If you absolutely needed to you could do this:
<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>
Rather than using $parent
it would be better to use object.property
as you have discovered.
Alternative
Also, another way of doing it would be to add an update method to your controller. Because of Scope Inheritance you could access the parent method in your ng-repeat and update the parent scopes selected
property:
//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>
Answered By - Abdullah Rasheed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.