1
我有一個叫做validate的指令會跨越表單並根據內置的角度輸入驗證指令自動驗證表單。該指令的一部分工作是循環顯示錶單上的子輸入,併爲數據驗證添加適當的工具提示。這發生在指令的編譯部分。問題是我在編譯函數中設置的數據綁定不在html中計算。例如指令中的編譯函數沒有正確評估
app.directive('validate', ["$timeout", "$compile", "gsap", function ($timeout, $compile, gsap) {
return {
scope: {
name: "@"
},
restrict: 'E',
replace: true,
controller: function ($scope) {
$scope.validate = {};
},
template: '<form name="{{name}}" ng-transclude></form>',
transclude: true,
compile: function compile(element, attr) {
//wrap this in a timeout function and wait for children to be available
//Have also tried this in the postLink function to the same result
$timeout(function() {
var selective = element.find('.validate');
if (selective.length > 0) {
$.each(selective, function (k, v) {
v.attr({
"tooltip": '{{validate.' + $(v).attr("name") + '}}',
"tooltip-trigger": '{{{true: "invalid", false: "valid"}[{{name}}.' + $(v).attr("name") + '.$invalid]}}'
});
});
} else {
$.each(element.find('input'), function (k, v) {
$(v).attr({
"tooltip": '{{validate.' + $(v).attr("name") + '}}',
"tooltip-trigger": '{{{true: "invalid", false: "valid"}[{{name}}.' + $(v).attr("name") + '.$invalid]}}'
});
});
}
});
return {
post: function postLink(scope, elem, attr, controller) {
//...a whole bunch of validation code, all works fine...
//should compile with attributes and resolved databindings
$compile(scope, elem, attr, controller);
}
};
}
};
}]);
這種評估在我的DOM
<input ng-model="username" type="email" placeholder="Username" name="username" ng-required="true" ng-minlength="2" class="ng-pristine ng-invalid ng-invalid-required ng-valid-email ng-valid-minlength" required="required" tooltip="{{validate.username}}" tooltip-trigger="{{{true: "invalid", false: "valid"}[{{name}}.username.$invalid]}}">
正如你看到的,屬性設置以下,但數據綁定不評價,因爲我會指望他們