If you want to monitor changes within the controller, consider using $scope.$watch
instead of a Service:
$scope.records.items.forEach(watchRecordValue);
function watchRecordValue(record){
$scope.$watch(function(){ return record.option; }, function(newVal, oldVal){
if(newVal !== oldVal){
$scope.records.submitOption(record);
}
});
}
However, this workaround is not ideal and should be avoided for cleaner, more maintainable code. It would be better to utilize ng-change
as it is simpler and faster. Simply modify the input tag in your HTML as follows:
<input name="options"
type="radio"
ng-model="item.option"
ng-change="records.submitOption(item)"
ng-value="option.id" />
(The only difference being the addition of
ng-change="records.submitOption(item)"
)
EDIT (Added "wrapper" solution):
If changing the form directly is not an option, consider wrapping the form in a custom directive. Here's an example:
myApp.directive('myWatch', [function () {
return {
restrict: 'A',
scope: {
myWatch: '=',
myHandler: '@',
},
link: function(scope, element, attr) {
scope.$watch('myWatch', function(newVal, oldVal){
if(newVal !== oldVal){
scope.$parent.$eval(attr.myHandler);
}
});
}
};
}]);
This allows you to keep your form unchanged by wrapping it:
<div my-watch="item.option" my-handler="records.submitOption(item)">
<form> <!-- Your original form contents here --> </form>
</div>
Here's the modified JSFiddle with this wrapper: http://jsfiddle.net/shjejb34/
Note: In most cases, using the ng-change
solution mentioned earlier is recommended over creating a new directive for this purpose.