Sunday, October 1, 2017

Added validation constraints to inputs dynamically, but Angular not initialising them

I have tried adding attributes such as ng-required="true" and ng-pattern="/^(d)+$/" dynamically as DOM is compiled by Angular. They are added and appear on the element when I inspect the element, however they do not appear to be initialised and do nothing.

I did this using the directive below, I pass the inp object into the directive scope from the template as it’s compiled, the inp object contains all the data about how the input should be rendered.

.directive ('addConstraints', function() {
    return {
        restrict: 'A',
        scope : {
          inp : '=inp'
        },
        link : function(scope, ele, attr)   {

                if(!scope.inp || !scope.inp.attributes) return;
                var attrs = scope.inp.attributes;

                for(var i = 0; i < attrs.length; i++) {
                ele.attr(attrs[i].attr, attrs[i].val);
            }

        }
}});

Use:

<div ng-controller="someController">

<div ng-repeat="inp in inputs">

<input ng-if="inp.type == 'text'" add-constraints inp="inp" type="text">

</div>

</div>

Using angularjs 1.5.8

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/01/added-validation-constraints-to-inputs-dynamically-but-angular-not-initialising-them/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment