Angularjs 动态添加html时不应用ng样式

Angularjs 动态添加html时不应用ng样式,angularjs,angularjs-ng-style,Angularjs,Angularjs Ng Style,我有一个表单,在这个表单中,只要点击一个按钮,字段就会被动态添加。 这是添加表单字段的函数 $scope.addFormField = function(){ let container = document.getElementById('formFieldContainer'); // a variable which keeps track of the number of fields added $scope.obj.fieldCount++; let

我有一个表单,在这个表单中,只要点击一个按钮,字段就会被动态添加。 这是添加表单字段的函数

$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]);
}
$scope.addFormField=function(){
let container=document.getElementById('formFieldContainer');
//跟踪添加的字段数的变量
$scope.obj.fieldCount++;
设formField='手机号码';
container.appendChild($compile(formField)($scope)[0]);
}
如果我直接用html编写表单字段代码,ng样式将得到正确应用。但是,如果使用上述函数添加表单字段,则不会应用ng样式


为了让ng style在动态添加的字段中工作,我还应该向代码中添加其他内容。

您可以在变量中设置
ng style
内容,然后在formField中使用它:

$scope.addFormField=function(){
let container=document.getElementById('formFieldContainer');
//根据条件设置变量
让newstyle=条件“{'border-color\':\'green\',\'color\':\'green\}”:0;
//跟踪添加的字段数的变量
$scope.obj.fieldCount++;
设formField='手机号码';
container.appendChild($compile(formField)($scope)[0]);
}

查看演示:

非常感谢!使用变量解决了我的问题。但是,您知道我之前使用的策略为什么不起作用吗?angular似乎没有重新编译动态添加的html字符串,以便计算三元表达式
$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]);
}