dman dman - 22 days ago 5
AngularJS Question

Angular Radio Button Not Firing On Watch

I have a watch on

region
but it is not firing when I click on the radio button.

Am I doing something wrong or is it because radio buttons only detect change once in angular? Anyway around this without using form?

<div class="filter-column">
<div class="filter-title">Region</div>
<div class="bottom-line"></div>
<div class="overflow-container">
<div ng-repeat="choice in regions| orderBy: 'description'">
<input type="radio"
value="{{choice.name}}"
name="regionRadio"
ng-model="region">
{{choice.description}}
</div>
</div>
</div>





$scope.$watchCollection(watchRMDapisPopulate,
populateRMDfiltersView);

function watchRMDapisPopulate() {
return regionMarketDealerSrv.orgFilterData;
}

function populateRMDfiltersView(newValue, oldValue) {
if (newValue) {
$scope.regions = newValue.regions;
}
}



$scope.$watch('region', radioButtonRegion);

function radioButtonRegion(regionName) {
console.log(regionName)
if (regionName === 'All') {
regionMarketDealerSrv.populateRegions();
} else {
regionMarketDealerSrv.populateMarkets(regionName);
}
}

Answer

The watch isn't able to pick up the changes correctly when using ng-model="region" since you are using primitive values. When you change the value you are getting a new reference. You can use a property of an object as your model and $watch that:

var app = angular.module('app', [])

app.controller('MyController', function($scope) {
  $scope.regions = [{
    name: 'a',
    description: 'region A'
  }, {
    name: 'b',
    description: 'region B'
  }];

  $scope.selected = {
    region: 'a'
  };

  $scope.$watch('selected.region', radioButtonRegion);

  function radioButtonRegion(newVal, oldVal) {
    if (newVal !== oldVal) {
      console.log(newVal, oldVal)
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyController">
  <div>Region</div>
  <div ng-repeat="choice in regions| orderBy: 'description'">
    <input type="radio" value="{{choice.name}}" name="regionRadio" ng-model="selected.region">{{choice.description}}
  </div>
</div>