AngularJS能夠經過ng-app來自動初始化模塊,也能夠經過angular.bootstrap(document, [module])手動啓動應用,無論用哪一種方法,應用啓動後,動態往dom樹裏面添加的dom元素,沒法執行angular指令,即沒法經過ng-model、ng-click給動態添加的dom元素綁定數據和事件,怎麼辦?javascript
動態添加dom元素的場景很是常見,如點擊某頁面上修改用戶資料的按鈕,發送ajax請求去查詢用戶資料,而後經過模板引擎將事先寫在頁面裏的靜態模板編譯成HTML字符串,最後將HTML字符串append到頁面顯示出來,通常狀況下咱們會這樣作:css
<!DOCTYPE html> <html ng-app="app"> <head> <title>demo</title> <meta charset="utf-8"/> <script src="http://cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.min.js"></script> <script id="others_angular_103" type="text/javascript" class="library" src="http://sandbox.runjs.cn/js/sandbox/other/angular.min.js"></script> <style> .contani{ width: 100%; height: 300px; border: 1px solid red; } </style> </head> <body ng-controller="myCtrl"> <script> var app = angular.module('app',[]); app.controller('myCtrl', ['$scope','$compile',function(scope,$compile){ scope.valchange = function(){ console.log('value change') } scope.edit = function(){ //假設這是ajax返回的數據 scope.username = 'wangmeijian'; scope.password = '000000'; $(".contani").html(myTmpl.innerHTML); } }]) </script> <button ng-click="edit()">修改資料</button> <div class="contani"></div> <script type="text/html" id="myTmpl"> <form> 用戶名:<input type="text" ng-model="username" /> 密碼:<input type="text" ng-model="password" /> </form> </script> </body> </html>
點擊修改資料按鈕,新插入的dom元素並無綁定ajax返回的數據,這是由於點擊按鈕前angular已經初始化完畢了,解決辦法固然不是再初始化一次,而是單獨使用$compile編譯靜態模板的HTML,而後再插入dom樹中html
<!DOCTYPE html> <html ng-app="app"> <head> <title>demo</title> <meta charset="utf-8"/> <script src="http://cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.min.js"></script> <script id="others_angular_103" type="text/javascript" class="library" src="http://sandbox.runjs.cn/js/sandbox/other/angular.min.js"></script> <style> .contani{ width: 100%; height: 300px; border: 1px solid red; } </style> </head> <body ng-controller="myCtrl"> <script> var app = angular.module('app',[]); app.controller('myCtrl', ['$scope','$compile',function(scope,$compile){ scope.valchange = function(){ console.log('value change') } scope.edit = function(){ //假設這是ajax返回的數據 scope.username = 'wangmeijian'; scope.password = '000000'; //$(".contani").html(myTmpl.innerHTML); $(".contani").append( $compile(myTmpl.innerHTML)(scope) ) } }]) </script> <button ng-click="edit()">修改資料</button> <div class="contani"></div> <script type="text/html" id="myTmpl"> <form> 用戶名:<input type="text" ng-model="username" ng-change="valchange()" /> 密碼:<input type="text" ng-model="password" ng-change="valchange()" /> </form> </script> </body> </html>
問題解決了。此時動態插入的元素就能夠執行angular指令了,客官能夠打開控制檯操做以上實例查看結果java