我有指示我动态添加其他指令和属性:
app.directive('lrDatetime', function ($compile) {
return {
restrict: 'AE',
require: ["ngModel"],
scope: {
ngModel: "=",
item: "="
},
templateUrl: "template.html",
compile: function compile(element, attrs) {
var datepicker = element.find(".lr-datepicker");
if (attrs.required === "true") {
datepicker.attr("ng-required", "true");
}
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controllers) {
$compile(iElement.contents())(scope);
}
};
},
controller: function ($scope) {
$scope.opened = false;
$scope.open = function ($event, obj, which) {
$scope.opened = true;
};
$scope.format= "dd.MM.yyyy";
}
};
});
模板:
<input type="text"
class="lr-datepicker"
is-open="opened"
uib-datepicker-popup="{{format}}"
datepicker-append-to-body="true"
ng-model="ngModel" />
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="open($event, item, 'isOpened')">
Open
</button>
</span>
现在当我将值绑定并尝试输入某些内容时,它会被删除。我知道如果模型无效,则将其设置为&#34; undefined&#34;,但如果我在指令之外执行相同的操作,则会保留输入的内容。
如果我只是将这些属性移动到模板并删除对$ compile的调用 - 一切都按预期工作。但是这种方法的巨大减少是我无法控制属性外观,它总是会被渲染。
我错过了什么?
答案 0 :(得分:1)
找到解决方案 - 应该在$ compile:
之前在链接函数中手动添加ngModel属性app.directive('lrDatetime', function ($compile) {
return {
restrict: 'AE',
require: ["ngModel", "^form"],
scope: {
ngModel: "=",
item: "=",
required: "=",
name: "@"
},
templateUrl: "template.html",
link: function (scope, element, attrs, controllers) {
scope.itemForm = controllers[1];
scope.opened = false;
scope.open = function ($event, obj, which) {
scope.opened = true;
};
scope.format= "dd.MM.yyyy";
var datepicker = element.find("input");
if (scope.required === true) {
datepicker.attr("ng-required", "true");
}
datepicker.attr("name", scope.name);
datepicker.attr("ng-model", "ngModel");
datepicker.attr("uib-datepicker-popup", scope.format);
$compile(element.contents())(scope);
}
};
});
模板:
<input type="text"
class="lr-datepicker"
is-open="opened"
datepicker-append-to-body="true" />
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="open($event, item, 'isOpened')">
Open
</button>
</span>
<span ng-if="itemForm[name].$error.required">required!</span>
认为问题会弹出,因为模板会被编译两次并且模型会被重新绑定。