Angularjs can be ng-app from the initialization module, or through the Angular.bootstrap (document, [module]) manually start the application, regardless of which method, after the application started, dynamically added to the DOM tree inside the DOM element, The angular directive cannot be executed, that is, data and events cannot be bound to dynamically added DOM elements through Ng-model, Ng-click.
The scene of adding DOM elements dynamically is very common, such as clicking on a page to modify the user Profile button, sending AJAX requests to query the user profile, and then through the template engine to write the static template written in the page as an HTML string, and finally the HTML string append to the page display, In general we will do this:
<! DOCTYPE html>. contani{Width:100%; height:300px; border:1px solid red; } </style>varApp = Angular.module (' app ',[]); App.controller (' Myctrl ', [' $scope ', ' $compile ',function(scope, $compile) {Scope.valchange=function() {Console.log (' Value change ')} Scope.edit=function(){ //Let's say this is the data returned by AjaxScope.username = ' Wangmeijian '; Scope.password= ' 000000 '; $(". Contani"). HTML (mytmpl.innerhtml); } }])</script><button ng-click= "edit ()" > Modify Data </button><div class= "Contani" ></div>< Script type= "text/html" id= "Mytmpl" > <form>User name:<input type= "text" ng-model= "username"/> Password: <input type= "text" ng-model= "password"/> </form> ;</script></body>View CodeClick the Modify Data button, the newly inserted DOM element is not bound to the data returned by Ajax, because the angular has been initialized before the button is clicked, the solution is not to initialize again, but to use $compile to compile the static template HTML separately and then insert the DOM tree
<! DOCTYPE html>. contani{Width:100%; height:300px; border:1px solid red; } </style>varApp = Angular.module (' app ',[]); App.controller (' Myctrl ', [' $scope ', ' $compile ',function(scope, $compile) {Scope.valchange=function() {Console.log (' Value change ')} Scope.edit=function(){ //Let's say this is the data returned by AjaxScope.username = ' Wangmeijian '; Scope.password= ' 000000 '; //$ (". Contani"). HTML (mytmpl.innerhtml);$ (". Contani"). Append ($compile (mytmpl.innerhtml) (Scope))}}])</script><button ng-click= "edit ()" > Modify Data </button><div class= "Contani" ></div>< Script type= "text/html" id= "Mytmpl" > <form>User name:<input type= "text" ng-model= "username" ng-change= "valchange ()"/> Password: <input type= "text" ng-model= "password "Ng-change=" Valchange () "/> </form></script></body>View CodeThe problem is solved. The dynamically inserted element can then execute the angular instruction, and Sir can open the console operation to view the results of the above instance
Angularjs initializing a static template