Created
February 24, 2016 12:41
-
-
Save ToxicWar/abc1e500d8cdb15925af to your computer and use it in GitHub Desktop.
Directive for edit yaml in textarea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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