您好,登錄后才能下訂單哦!
這篇文章主要介紹Angularjs如何動(dòng)態(tài)添加指令并綁定事件,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
先說使用場(chǎng)景,動(dòng)態(tài)生成DOM元素并綁定事件,非常常見的一種場(chǎng)景,用jq實(shí)現(xiàn)效果:
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應(yīng)該怎么實(shí)現(xiàn)呢?想當(dāng)然的情況是這樣的:
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) } }])
理想很豐滿,點(diǎn)擊test的時(shí)候內(nèi)容確實(shí)變成了input,但是input不能綁定任何ng事件。
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) } }])
達(dá)到目的~
這里用到了$compile服務(wù),官方的解釋是compile可以將一個(gè)HTML字符串或者DOM編譯成模板,該模板能夠與scope鏈接起來,也就是說直接插入一段html片段到頁面中,雖然能插入進(jìn)去,但是angular并沒有編譯,所以任何ng事件指令綁定都是無效的,通過compile能夠?qū)tml片段先編譯后再插入。
以上是“Angularjs如何動(dòng)態(tài)添加指令并綁定事件”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。