I have a web page with some HTML elements which I cannot edit. I'd like to dynamically attach ng-model attributes to these and have AngularJS re-bind them to the scope. A simplified example of what I want to accomplish can be found here
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script>
function MyCtrl($scope) {
$scope.myModel1 = "Hi";
$scope.myModel2 = "there";
var myModel2 = angular.element("#myModel2");
//This won't work
myModel2.attr("ng-model", "myModel2");
}
</script>
<div ng-app ng-controller="MyCtrl">
<input type="text" ng-model="myModel1"/>
<!-- I can't touch this -->
<input type="text" id="myModel2" />
</div>
You need to use $compile
(docs)
$compile(myModel2.attr("ng-model", "myModel2"))($scope);
demo
When you load your page, angular uses $compile
on the HTML automatically, that's how it knows which elements to assign which directives to. If you just change the attribute like you tried, angular doesn't know. You have to use $compile
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With