动态添加ng-pattern,缺少验证类(Dynamically adding ng-pattern, missing validation classes)
我正在尝试从指令中动态添加和删除“ng-pattern”属性。 这是我的指示:
ap.directive('myDirective', ['$compile', function ($compile) { return { scope: { test: "=myDirective" }, link: function ($scope, element, attrs) { $scope.$watch('test', function () { if (someCondition) { element.removeAttr("ng-pattern"); } else { element.attr("ng-pattern", "/^([0-9]{5})$|^([0-9]{9})$/"); } }); } }; }]);和来自html的输入标签:
<form name="myform" novalidate> <input name="test" required class="form-control" ng-model="myModel" my- directive="someValueFromScope"/> </form>如果我从Chrome开发工具检查DOM元素,则会将“ng-pattern”属性添加到输入标记,但不会添加验证类(ng-invalid-pattern或ng-valid-pattern)。 如果我直接从html添加“ng-pattern”,一切都按预期工作。
I'm trying to dynamically add and remove, from a directive, the "ng-pattern" attribute. Here's my directive:
ap.directive('myDirective', ['$compile', function ($compile) { return { scope: { test: "=myDirective" }, link: function ($scope, element, attrs) { $scope.$watch('test', function () { if (someCondition) { element.removeAttr("ng-pattern"); } else { element.attr("ng-pattern", "/^([0-9]{5})$|^([0-9]{9})$/"); } }); } }; }]);And the input tag from the html:
<form name="myform" novalidate> <input name="test" required class="form-control" ng-model="myModel" my- directive="someValueFromScope"/> </form>If I inspect the DOM elements from Chrome dev tools, the "ng-pattern" attribute is added to the input tag, but the validation classes (ng-invalid-pattern or ng-valid-pattern) are not added. If I add the "ng-pattern" directly from the html, everything works as expected.
最满意答案
使用$ compile和$ set为: -
attrs.$set("ng-pattern", "/^([0-9]{5})$|^([0-9]{9})$/"); $compile(element)($scope);I finally figured it out, compiling the parent scope did the trick.
$compile(element)($scope.$parent)更多推荐
发布评论