我正在尝试编写一个“只读”指令,它将输入(使用ng-model)转换为具有该模型值的跨度。我想通过简单地将“my-read-only”属性添加到元素来实现这一目的。
请参阅: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" />
我试图给my-read-only指令赋予更高的优先级。这允许文本框绑定到模型,但不再使用跨度。
如果my-read-only未设置为true,我如何实现“切换”元素内容并仍保留原始元素?看来ng-model正在首先在元素上编译,当我转换时会丢失。
答案 0 :(得分:0)
可以更改为使用ng-bind
的范围,如下所示:
mod.directive("myReadOnly", function ($compile) {
return {
restrict: "A",
link:function(scope,elem,attrs){
if(attrs.myReadOnly=='true'){
var template=$compile('<span ng-bind="'+attrs.ngModel+'"></span>')(scope)
elem.replaceWith(template);
}
}
}
});
的 DEMO 强>