Angularjs 動(dòng)態(tài)添加指令并綁定事件的方法
這兩天學(xué)習(xí)了angularjs 感覺指令這個(gè)地方知識(shí)點(diǎn)挺多的,而且很重要,所以,今天添加一點(diǎn)小筆記。
先說使用場(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片段先編譯后再插入。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Angularjs為ng-click事件傳遞參數(shù)
- angular ng-click防止重復(fù)提交實(shí)例
- AngularJS基礎(chǔ) ng-click 指令示例代碼
- AngularJS的ng-click傳參的方法
- 詳解angularJS動(dòng)態(tài)生成的頁面中ng-click無效解決辦法
- AngularJS中directive指令使用之事件綁定與指令交互用法示例
- Angularjs中使用指令綁定點(diǎn)擊事件的方法
- AngularJs ng-change事件/指令的用法小結(jié)
- Angularjs 事件指令詳細(xì)整理
- Angular使用操作事件指令ng-click傳多個(gè)參數(shù)示例
相關(guān)文章
Angular 多級(jí)路由實(shí)現(xiàn)登錄頁面跳轉(zhuǎn)(小白教程)
這篇文章主要介紹了Angular 多級(jí)路由實(shí)現(xiàn)登錄頁面跳轉(zhuǎn)(小白教程),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
angular1.x ui-route傳參的三種寫法小結(jié)
今天小編就為大家分享一篇angular1.x ui-route傳參的三種寫法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08
AngularJS ng-bind-template 指令詳解
本文注意介紹AngularJS ng-bind-template 指令,這里把相關(guān)資料整理了一下,并附實(shí)例代碼,有需要的小伙伴可以參考下2016-07-07
詳解angularJs模塊ui-router之狀態(tài)嵌套和視圖嵌套
這篇文章主要介紹了詳解angularJs模塊ui-router之狀態(tài)嵌套和視圖嵌套,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04

