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片段先編譯后再插入。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM