Skip to content

Instantly share code, notes, and snippets.

@andrewstuart
Created September 17, 2015 21:28
Show Gist options
  • Save andrewstuart/1d68b8b14a767950e115 to your computer and use it in GitHub Desktop.
Save andrewstuart/1d68b8b14a767950e115 to your computer and use it in GitHub Desktop.
Angular Default Value Directive
app.directive('defaultValue', function() {
/**
* @ngdoc directive
* @name App.directive:defaultValue
* @param {Expression} defaultValue An angular expression for the default
* value of the model
* @requires ngModel
* @description the `default-value` directive allows you to set some
* dynamic default value for anything with an `ngModel`. The model value
* will be updated every time the expression changes, unless the value is
* changed. If the value is changed, updates will no longer occur unless the
* model value is cleared out completely, in which case updates will
* continue.
* @restrict CA
*/
return {
restrict: 'CA',
require: 'ngModel',
scope: {
defaultValue: '='
},
link: function($scope, iEle, iAttrs, ngModel) {
var doUpdates = true;
$scope.$watch('defaultValue', function(newVal, oldVal) {
if ( !ngModel.$modelValue ) {
doUpdates = true;
} else if ( ngModel.$modelValue !== oldVal ) {
doUpdates = false;
}
if ( !doUpdates ) { return; }
ngModel.$setViewValue(newVal);
ngModel.$render();
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment