标签:
AngularJS可以通过ng-app来自动初始化模块,也可以通过angular.bootstrap(document, [module])手动启动应用,不管用哪种方法,应用启动后,动态往dom树里面添加的dom元素,无法执行angular指令,即无法通过ng-model、ng-click给动态添加的dom元素绑定数据和事件,怎么办?
动态添加dom元素的场景非常常见,如点击某页面上修改用户资料的按钮,发送ajax请求去查询用户资料,然后通过模板引擎将事先写在页面里的静态模板编译成HTML字符串,最后将HTML字符串append到页面显示出来,一般情况下我们会这样做:
<!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树中
<!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指令了,客官可以打开控制台操作以上实例查看结果
标签:
原文地址:http://www.cnblogs.com/wangmeijian/p/5128916.html