欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angularjs 動態(tài)添加指令并綁定事件的方法

 更新時間:2017年04月13日 11:57:54   作者:彼岸花在開  
本篇文章主要介紹了Angularjs 動態(tài)添加指令并綁定事件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

這兩天學(xué)習(xí)了angularjs 感覺指令這個地方知識點挺多的,而且很重要,所以,今天添加一點小筆記。

先說使用場景,動態(tài)生成DOM元素并綁定事件,非常常見的一種場景,用jq實現(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)該怎么實現(xiàn)呢?想當然的情況是這樣的:

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的時候內(nèi)容確實變成了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服務(wù),官方的解釋是compile可以將一個HTML字符串或者DOM編譯成模板,該模板能夠與scope鏈接起來,也就是說直接插入一段html片段到頁面中,雖然能插入進去,但是angular并沒有編譯,所以任何ng事件指令綁定都是無效的,通過compile能夠?qū)tml片段先編譯后再插入。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論