Skip to content

Instantly share code, notes, and snippets.

@ry8806
Last active January 27, 2017 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ry8806/84f5234c7c41b5d8b5deafc10f0c8773 to your computer and use it in GitHub Desktop.
Save ry8806/84f5234c7c41b5d8b5deafc10f0c8773 to your computer and use it in GitHub Desktop.
function isDefinedAndNotNull(property) {
return property !== undefined && property !== null;
};
angApp.directive("radioTrackBy", [function () {
return {
restrict: "A",
scope: {
ngModel: "=",
ngValue: "=",
radioTrackBy: "@"
},
link: function (ng, el, attrs) {
// Set up the watch and reference it so we can remove it when we've got that initial piece of data
var unWatch = ng.$watch(attrs.ngModel, function (newValue) {
if (isDefinedAndNotNull(ng.ngModel) && isDefinedAndNotNull(ng.ngModel[ng.radioTrackBy])) {
// The model has been populated
if (ng.ngValue[ng.radioTrackBy] === ng.ngModel[ng.radioTrackBy]) {
// The track-by property (from the radio's source list) and model property (currently selected radio button) match, set the model object to the matched object
ng.ngModel = ng.ngValue;
}
// We don't want to watch this anymore
unWatch();
}
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment