ng-style not getting applied in case of dynamically added html

All we need is an easy explanation of the problem, so here it is.

I have a form in which fields get added dynamically upon a button click.
This is the function which adds the form fields

$scope.addFormField = function(){
    let container = document.getElementById('formFieldContainer');
    // a variable which keeps track of the number of fields added
    $scope.obj.fieldCount++;
    let formField = '<md-input-container><label>Mobile Number</label><input type="text" required name="mobileNo_' + $scope.obj.fieldCount + '" ng-model="obj.mobileNumberArr[' + $scope.obj.fieldCount +']" ng-pattern="/^[1-9]{1}[0-9]{9}$/" ng-style="form.mobileNo_' + $scope.obj.fieldCount + '.$valid ? {\'border-color\': \'green\',\'color\': \'green\'}:0"></md-input-container>';
    container.appendChild($compile(formField)($scope)[0]);
}

If I write the form field code directly in html, the ng-style gets applied correctly. But, if I use the above function to add form fields, the ng-style does not get applied.

Is there anything else that I should be adding to my code in order to get ng-style to work in dynamically added fields.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can set ng-style content in a variable and then use it in the formField:

$scope.addFormField = function(){
    let container = document.getElementById('formFieldContainer');

    // SET VARIABLE BASED ON CONDITION
    let newstyle = condition ? "{\'border-color\': \'green\',\'color\': \'green\'}" : 0;

    // a variable which keeps track of the number of fields added
    $scope.obj.fieldCount++;
    let formField = '<md-input-container><label>Mobile Number</label><input type="text" required name="mobileNo_' + $scope.obj.fieldCount + '" ng-model="obj.mobileNumberArr[' + $scope.obj.fieldCount +']" ng-pattern="/^[1-9]{1}[0-9]{9}$/" ng-style="' + newstyle + '"></md-input-container>';
    container.appendChild($compile(formField)($scope)[0]);
}

Check a demo : DEMO

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply