I am fairly new to AngularJS.
I am trying to bind an object to a textarea.
HTML:
Here is our JSON directive with validity checks:
app.directive('jsonInput', function () {
'use strict';
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function(input) {
try {
var obj = JSON.parse(input);
ctrl.$setValidity('jsonInput', true);
return obj;
} catch (e) {
ctrl.$setValidity('jsonInput', false);
return null;
}
});
ctrl.$formatters.unshift(function(data) {
if (data == null) {
ctrl.$setValidity('jsonInput', false);
return "";
}
try {
var str = JSON.stringify(data);
ctrl.$setValidity('jsonInput', true);
return str;
} catch (e) {
ctrl.$setValidity('codeme', false);
return "";
}
});
}
};
});
When the user enters invalid JSON, the model is null. When the model contains circular references or is null, the user will see an empty string ("") and the input is invalid.
Enjoy.