Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: late-binding of ng-model to dom element

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>
like image 752
matteo Avatar asked Apr 08 '14 10:04

matteo


1 Answers

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.

like image 160
Mosho Avatar answered Sep 20 '22 18:09

Mosho