SoFunction
Updated on 2025-04-11

Angularjs method to dynamically add directives and bind events

I have learned angularjs in the past two days. I feel that there are a lot of knowledge points in the instruction place and it is very important, so I will add a little note today.

Let’s talk about the usage scenario first, dynamically generate DOM elements and bind events. It is a very common scenario, using jq to achieve the effect:

var count=0;
$("#test").on("click",function(event){
 if(()=="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());
})

How should I achieve it if I use angularjs? The situation is this:

var myApp = ('myApp', []);
    ('MainCtrl', ['$scope','$compile',function($scope) {
      $ = 0;
      $ = function() {
       if(()=="input")return;
        var target=$();
        $++;
        ("<input value='"+$+"' ng-blur='showValue()'>" );
      }
      $=function(){
        alert()
      }
    }])

The ideal is full. When clicking test, the content does become input, but the input cannot bind any ng events.

var myApp = ('myApp', []);
    ('MainCtrl', ['$scope','$compile',function($scope, $compile) {
      $ = 0;
      $ = function() {
       if(()=="input")return;
        var target=$();
        $++;
        ($compile("<input value='"+$+"' ng-blur='showValue()'>")($scope));
      }
      $=function(){
        alert()
      }
    }])

Achieve the goal ~

Used here$compileService, the official explanation is that compile can compile an HTML string or DOM into a template, which can be linked to scope, that is, insert a html fragment directly into the page. Although it can be inserted, angular is not compiled, so any ng event instruction binding is invalid. Compile can compile the html fragment first and then insert it.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.