Angularjs looks at radio button for change, only working on first selection
So I have a list of radio buttons and I am trying to watch the selection change using $ watch in a directive. I can only call the clock when I first select these items.
My html:
<p ng-repeat="(key,item) in option" style="margin-bottom:0px ">
<label>
<input type="radio" is-valid ng-model="value" selected-key="value" name="select" value="{{key}}" ng-checked="getChecked($index)"> {{item.name}}
</label>
</p>
My directive returns:
return {
restrict: "A",
scope: {
selectedKey: '='
},
link: function(scope, elem, attrs) {
scope.$watch('selectedKey', function(newValue, oldValue, scope) {
alert('triggered')
});
}
}
What am I doing wrong? I tried to watch with "value" only, but the clock won't start.
Thank you in advance
source to share
You need to understand what ngRepeat
creates a new area for each element of the iteration. This means that it value
is individual for each switch. As a result, the watch expression will be triggered only once per radio input, after that it will not change.
What you need to do is use a parent area model holding the selected radio value. You can achieve this by declaring the model in your controller, for example:
$scope.radio = {value: null};
and use this model for every switch. Also, I dropped the redundant attribute selected-key
, you don't need it since you already have ng-model pointing to the same radio.value
.
All together the directive will look like this:
app.directive('isValid', function() {
return {
restrict: "A",
scope: {
selectedKey: '=ngModel'
},
link: function(scope, elem, attrs) {
scope.$watch('selectedKey', function(newValue, oldValue, scope) {
console.log('triggered')
});
}
};
});
source to share