Skip to content

Instantly share code, notes, and snippets.

@ToxicWar
Created February 24, 2016 12:41
Show Gist options
  • Save ToxicWar/abc1e500d8cdb15925af to your computer and use it in GitHub Desktop.
Save ToxicWar/abc1e500d8cdb15925af to your computer and use it in GitHub Desktop.
Directive for edit yaml in textarea
'use strict';
var angular = require('angular'),
yaml = require('js-yaml');
(function (angular, undefined) {
var app = angular.module('example-app');
app.directive('yamlEdit', function () {
return {
restrict: 'A',
require: 'ngModel',
template: '<textarea ng-model="yamlEditing"></textarea>',
replace: true,
scope: {
model: '=yamlEdit'
},
link: function (scope, element, attrs, ngModelCtrl) {
function setValid() {
ngModelCtrl.$setValidity('yaml', true);
}
function setInvalid() {
ngModelCtrl.$setValidity('yaml', false);
}
function string2yaml(text) {
try {
return yaml.safeLoad(text);
} catch (err) {
setInvalid();
return text;
}
}
function setEditing(value) {
scope.yamlEditing = angular.copy(yaml.safeDump(value));
}
function updateModel(value) {
scope.model = string2yaml(value);
}
function isValidyaml(model) {
var flag = true;
try {
angular.fromyaml(model);
} catch (err) {
flag = false;
}
return flag;
}
//init
setEditing(scope.model);
//check for changes going out
scope.$watch('yamlEditing', function (newval, oldval) {
if (newval !== oldval) {
if (isValidyaml(newval)) {
setValid();
updateModel(newval);
} else {
setInvalid();
}
}
}, true);
//check for changes coming in
scope.$watch('model', function (newval, oldval) {
if (newval !== oldval) {
setEditing(newval);
}
}, true);
}
};
});
}(angular));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment