简体   繁体   中英

ng-pattern not working for dynamically added input tag in angular

I have a input tag in a variable with ng-pattern when I inserted it into a div its ng-pattern is not working

style:

.from_fields {
    transition: all linear 0.5s;
    background: transparent;
}
.from_fields.ng-invalid {
    color: white;
    background: red;
}

Script

$scope.input='<input type="text" ng-pattern="/^[0-9]{1,7}$/" class="from_fields">';
angular.element(document.getElementById('test')).html($scope.input);

can someone help??

The string you are trying to enter needs to be compiled for angular to have it in its watch list and have any ng attributes evaluated.

Right now ng-pattern is a regular custom data attribute with no meaning to angular

If you dont want to bind in an angular controller just remove the ng-

leaving

'<input type="text" pattern="^[0-9]{1,7}$" class="from_fields">';

note that the pattern attribute does not need slashes

otherwise you will have to import in your controller the $compile service

and compile the string given a $scope variable

var input = '<input type="text" ng-pattern="^[0-9]{1,7}$" class="from_fields">';
var compiled_input = $compile(input)($scope)

and the append it to the document

angular.element(<selector>).append(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM