日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Angularjs 动态添加指令并绑定事件

發布時間:2023/12/19 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Angularjs 动态添加指令并绑定事件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

先說使用場景,動態生成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片段先編譯后再插入。

?

轉載于:https://www.cnblogs.com/hutuzhu/p/6674797.html

總結

以上是生活随笔為你收集整理的Angularjs 动态添加指令并绑定事件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。