动态添加ng

编程入门 行业动态 更新时间:2024-10-11 23:18:59
动态添加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)

更多推荐

本文发布于:2023-08-02 07:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372398.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   ng

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!