指令动态创建NG-模式 [英] Directive to dynamically create an ng-pattern

查看:106
本文介绍了指令动态创建NG-模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个输入指令,将动态创建一个 NG-pattern元素来为您在输入字段有效的IP地址。所有我试图这样做的已经完全成功。虽然我可以动态修改其他属性,我不能创建一个 NG-模式,这将影响到 $有效状态

I'm trying to create a directive for an input element that will dynamically create an ng-pattern to check for a valid IP address in the input field. All of my attempts to do so have been completely unsuccessful. While I can dynamically modify other attributes, I can't create an ng-pattern that will affect the $valid status.

这里的code,我一直在努力,这似乎像它应该工作,但它不会做任何的 NG-模式

Here's the code that I've been working on which seems like it should work, but it doesn't do anything to the ng-pattern.

app.directive('ipAddress', function($parse) {
    return {
        link: function(scope, element, attrs) {
            var model = $parse(attrs.ngPattern);
            model.assign(scope, "/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/");
            scope.$apply();
        };
});

指令:

<input ng-model="ip" ip-address required type="text" id="inputIP" placeholder="xxx.xxx.xxx.xxx">

是的,我知道我可以只指定与 NG-模式内联&LT;输入&GT; 标记,但问题是,我希望能够在code动态地做到这一点,我想保持在&LT;输入&GT;通过不嵌入标签清洁一堆正则表达式code那里。

Yes, I know I can just specify the ng-pattern inline with the <input> tag but the point is that I want to be able to do this dynamically in the code, and I'd like to keep the <input> tag cleaner by not embedding a bunch of regex code there.

谁能帮帮我吗?谢谢!

推荐答案

您可以在控制器中定义模式,然后在HTML中使用:

You can define pattern in controller and then use in html:

$scope.pat=/^.*$/

然后在HTML

And then in html

<input ng-pattern="pat" ... >

这篇关于指令动态创建NG-模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆