Angular dynamic ngPattern

我怕爱的太早我们不能终老 提交于 2019-12-12 20:39:53

问题


I'm trying to implement dynamic ngPattern.

My regex changes when the user clicks on a button or selects a value from dropdown.

But for some reason this doesnt seem to work. Below is the code.

 app.controller('testController',function(){

    $scope.pattern = new RegExp('^\w{1,10}$');

    $scope.changePattern = function () {
        $scope.pattern = new RegExp('^\d{5}$');
    };

 });

But when i try something like this, it works.

    $scope.pattern = /^\w{1,10}$/;

    $scope.changePattern = function () {
        $scope.pattern = /^\d{5}$/;
    };

I'm not sure why using new RegExp() is not working. The reason I had to use new RegExp() is that I get this in a JSON response as string.


回答1:


This is because backlash (\) is a special character that you need to escape with "\\" when you are constructing a string:

$scope.pattern = new RegExp('^\\w{1,10}$');

So this has nothing to do with RegExp or with ng-pattern.



来源:https://stackoverflow.com/questions/30043768/angular-dynamic-ngpattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!