先說使用場景,動態生成DOM元素並綁定事件,非常常見的一種場景,用jq實現效果:
http://jsbin.com/gajizuyuju/edit?html,js,output
var count=0; $("#test").on("click",function(event){ if(event.target.tagName.toLowerCase()=="input") return; count++; var html="<input type='text' class='newEle' value='"+count+"'/>"; $(this).html(html); $(".newEle").focus(); }); $("body").on("blur",".newEle",function(){ alert($(this).val()); })
如果用angularjs應該怎么實現呢?想當然的情況是這樣的:
var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', ['$scope','$compile',function($scope) { $scope.count = 0; $scope.add = function() { if(event.target.tagName.toLowerCase()=="input")return; var target=$(event.target); $scope.count++; target.html("<input value='"+$scope.count+"' ng-blur='showValue()'>" ); } $scope.showValue=function(){ alert(event.target.value) } }])
理想很豐滿,點擊test的時候內容確實變成了input,但是input不能綁定任何ng事件。
稍微修改下:http://jsbin.com/zujalapone/edit?html,js,output
var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', ['$scope','$compile',function($scope, $compile) { $scope.count = 0; $scope.add = function() { if(event.target.tagName.toLowerCase()=="input")return; var target=$(event.target); $scope.count++; target.html($compile("<input value='"+$scope.count+"' ng-blur='showValue()'>")($scope)); } $scope.showValue=function(){ alert(event.target.value) } }])
達到目的~
這里用到了$compile服務,官方的解釋是compile可以將一個HTML字符串或者DOM編譯成模板,該模板能夠與scope鏈接起來,也就是說直接插入一段html片段到頁面中,雖然能插入進去,但是angular並沒有編譯,所以任何ng事件指令綁定都是無效的,通過compile能夠將html片段先編譯后再插入。