Object equality comparison for input[radio] with ng-model and ng-value

后端 未结 5 1086
长情又很酷
长情又很酷 2020-12-16 14:59

Let me start by saying that this question is very similar to issues with selection in a // // // See https://stackoverflow.com/questions/19281404/object-equality-comparison-for-inputradio-with-ng-model-and-ng-value // for the SO question that inspired this directive. return { scope: { radioOptions: '=', selectedOption: '=', ngValue: '=' }, link: function( scope, elem, attrs ) { var modelChanged = function() { if( jQuery.isArray(scope.radioOptions) ) { jQuery.each( scope.radioOptions, function(idx, item) { // This uses our models' custom 'equals' function for comparison, but another application could use // ID propeties, etc. if( typeof item.equals === 'function' && item.equals(scope.selectedOption) ) { elem.prop( 'checked', item === scope.ngValue ); } }); } }; scope.$watch( 'radioOptions', modelChanged ); scope.$watch( 'selectedOption', modelChanged ); var viewChanged = function() { var checked = elem.prop( 'checked' ); if( checked ) { scope.selectedOption = scope.ngValue; } }; elem.bind( 'change', function() { scope.$apply( viewChanged ); }); } }; });

提交回复
热议问题