Angularjs 動態(tài)添加指令并綁定事件的方法
這兩天學習了angularjs 感覺指令這個地方知識點挺多的,而且很重要,所以,今天添加一點小筆記。
先說使用場景,動態(tài)生成DOM元素并綁定事件,非常常見的一種場景,用jq實現效果:
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事件。
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片段先編譯后再插入。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
AngularJS ng-bind-template 指令詳解
本文注意介紹AngularJS ng-bind-template 指令,這里把相關資料整理了一下,并附實例代碼,有需要的小伙伴可以參考下2016-07-07
詳解angularJs模塊ui-router之狀態(tài)嵌套和視圖嵌套
這篇文章主要介紹了詳解angularJs模塊ui-router之狀態(tài)嵌套和視圖嵌套,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04

