Sibi Raj Sibi Raj - 1 month ago 10
AngularJS Question

Angular ng-model in appended Html code not working

This is my code. Where I dynamically add html on a button click.but the ng-model which I gave there is not working.

Can anyone solve my issue

$scope.addParam = function(selected) {
if (selected == "bucket_policy_privacy_status") {
var myElement = angular.element(document.querySelector('#inputParameters'));
myElement.append('<input type="text" style="width:220px" class="form-control" name="" disabled="" value=' + selected + '> <select class="form-control" style="width:196px" ng-model="fields.privacyStatus" ><option value="range">Range</option><option value="public">Public</option><option value="private">Private</option></select> <br><br>');
$scope.$watch('fields.privacyStatus', function() {
var privacy_status = $scope.fields.privacyStatus;
alert();
var status = {
"term": {}
}
status.term[selected] = privacy_status;
output.push(status);
});
$('#params option[value="bucket_policy_privacy_status"]').remove();
$scope.input.select = "bucket_owner";
}
};

Answer

There are a few things you will need to change:

You need to use Angulars $compile option to evaluate angular attributes/expressions when inserting HTML dynamically.

Adding the line below after you added the element ot the DOM should do the trick:

$compile(angular.element('.form-control'))($scope);

It basically just let's angular know there is something new it should evaluate and start watching.

(Don't forget to add $compile to your module dependencies).

Further to that I assume you have actually added an object called fields on your $scope?

Another thing you could do is use ng-change on your form instead of using $watch. The function you bind on ng-change would be invoked every time one of the selects in your form changes.

For further reading have a look at this: https://docs.angularjs.org/api/ng/service/$compile