问题
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