Skip to content

Instantly share code, notes, and snippets.

@xiel
Created November 13, 2015 11:06
Show Gist options
  • Save xiel/e94b4daca631a58969dd to your computer and use it in GitHub Desktop.
Save xiel/e94b4daca631a58969dd to your computer and use it in GitHub Desktop.
initialValue attribute directive for angular
/** Get and Render initial value from HTML attr (data from BackEnd)
* license: MIT
*/
angular.module('bra.global.directive')
.directive('initialValue', ['$parse', function($parse) {
'use strict';
//trim input values (eg. textareas)
var removeIndent = function (str) {
if(!str || typeof str !== 'string'){
return str
}
var lineStrings = str.split('\n');
var newLineStrings = [];
lineStrings.forEach(function (it, i) {
var trimmedLine = it.replace(/(^\s+|\s+$)/g,'');
if(trimmedLine){
newLineStrings.push(trimmedLine)
}
});
return newLineStrings.join('\n');
};
return {
restrict : 'A',
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var currentValue = $parse(attrs.ngModel)(scope);
var initialMarkupValue = element[0].value || attrs.value || attrs.initialValue;
var newValue;
if(initialMarkupValue && currentValue === undefined && currentValue != initialMarkupValue){
newValue = removeIndent(initialMarkupValue);
// update the model
modelCtrl.$setViewValue( newValue );
// update the view
modelCtrl.$render();
}
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment