I am trying to write a "read-only" directive that will transform an input (with ng-model) to a span that has the value of that model. I would like to do this by simply adding "my-read-only" attribute to an element.
See: http://jsfiddle.net/cbW83/4/
angular.module("myapp", []).directive("myReadOnly", [function () {
return {
restrict: "A",
transclude: "element",
require: "?ngModel",
priority: 100,
compile: function (tElem, tAttrs, transclude) {
var template = angular.element("<span></span>");
return function (scope, elem, attrs, ngModelCtrl) {
if (ngModelCtrl && scope.$eval(attrs.myReadOnly) === true) {
scope.$watch(function () {
return scope.$eval(attrs.ngModel);
}, function (newVal) {
template.html(newVal);
});
elem.after(template);
}
else {
elem.after(transclude(scope));
}
}
}
}
}]);
<!--Read-Only Directive set to false:-->
<input type="text" ng-model="user.firstname" my-read-only="false" />
I have tried to give the my-read-only directive a higher priority. This allows the textbox to bind to the model, but the span is no longer used.
How can I achieve "toggling" the elements contents and still retain the original element if my-read-only is not set to true? It appears ng-model is being compiled on the element first and this is lost when I transclude.