This example describes the method that Angularjs implements to bind events to dynamically generated elements. Share to everyone for your reference, specific as follows:
1. We know that in jquery, dynamically generating an element, if you want to dynamically bind events while dynamically generating elements, you can use the Live/on method (the Bind method has been abolished in jquery3.0).
2. In Angularjs, the operation Dom is generally done in the instruction, the event listener mechanism is in the case of the DOM binding event that has been statically generated, and if the DOM node is generated dynamically in the instruction, the dynamically generated node will not be monitored by the JS event.
For example:
Angular.module (' MyApp ', [])
. Directive (' MyText ', function () {return{restrict: '
A ',
Template: ' <div ng-click= "Hello ()" >hi everyone</div> ',
link:function (scope,ele,attr) {
}
}
})
In this directive, a new DOM node is generated:
<div ng-click= "Hello ()" >hi everyone</div>
But if you do not, the Ng-click event here is not possible, because the listener for the event is complete when the static HTML page is generated. So how do you give dynamically generated elements, bind events, and implement dynamic monitoring of events?
3. Compile the DOM through the $compile service to implement dynamic event binding
var template: ' <div ng-click= ' hello () ' >hi everyone</div> ',
var content = $compile (template) (scope);
Through these two sentences, first compile the DOM, and then add the compiled DOM to the previous static node, you can implement dynamic binding events, such as attention, should be injected into the $compile service
. directive (' MyText ', function ($compile) {})
The complete code is as follows:
Angular.module (' MyApp ', [])
. Directive (' MyText ', function ($compile) {
var template: ' <div ng-click= ' Hello () ">hi everyone</div> ',
return{
restrict: ' A ',
link:function (scope,ele,attr) {
Ele.on ( ' Click ', Function () {
scope. $apply (function () {
var content = $compile (template) (scope);
Element.append (content);
})
})
More readers interested in ANGULARJS related content can view the site topics: "Angularjs Introduction and Advanced Tutorials" and "ANGULARJS MVC Framework Summary"
I hope this article will help you to Angularjs program design.