StackOverflow_23790239: ng-change-event-only-fires-once-for-each-radio-button-when-created-with-ng-repea
Illustration of answer to http://stackoverflow.com/questions/23790239/ng-change-event-only-fires-once-for-each-radio-button-when-created-with-ng-repea.
by ExpertSystem
HTML
<div ng-app="MyApp">
<radio-environment environment="environment" change-environment="environmentChange()"></radio-environment>
<div style="margin-top: 15px;">
App Environment: {{ environment }}
</div>
</div>
JavaScript
angular.module('MyApp', [])
.controller('mainController', ['$scope'],
function(scope) {
scope.environmentChange = function() {
console.log('Changing to environment ' + scope.environment);
};
scope.watch("environment", function(newValue, oldValue) {
scope.environmentChange();
});
})
.directive('radioEnvironment', function() {
return {
scope: {
environment: '=' // two-way binding
},
restrict: 'E',
replace: true,
template: '<div><label ng-repeat="choice in choices">'
+ '<input type="radio" name="env" ng-model="local.environment" ng-change="changeEnvironment(choice)" value="{{ choice.id }}" />{{ choice.name }}'
+ '</label>'
+ '<div>Directive environment: {{ environment }}</div>'
+ '</div>',
link: function(scope, element, attributes) {
scope.choices = [
{ id: 1, name: "Testing" },
{ id: 2, name: "Production" }
];
scope.local = {environment: scope.environment};
scope.changeEnvironment = function(choice) {
scope.environment = choice.id;
};
/* Watch for changes in `scope.environment`
* from outside the directive */
scope.$watch('environment', function (newValue) {
scope.local.environment = newValue;
});
}
};
});