Joe Joe - 3 years ago 202
AngularJS Question

How to attach event to dom created in link function

I know that dom created in template function can be attached to an event in controller.As:

angular.module('app', [])
.directive('appClick', function(){
return {
restrict: 'A',
scope: true,
template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
controller: function($scope, $element){
$scope.clicked = 0;
$scope.click = function(){
$scope.clicked++
}
}
}
});


As there is no scope in template so I have to use link function.
The same how can I achieve in link function. Like:

angular.module('app', [])
.directive('appClick', function(){
return {
restrict: 'A',
scope: true,
link:function(scope, element, attrs){
element.html('<button ng-click="click()">Click me</button> Clicked {{clicked}} times')
},
controller: function($scope, $element){
$scope.clicked = 0;
$scope.click = function(){
$scope.clicked++
}
}
}
});


How to attach event here.

Answer Source

In Angularjs when you want to attach some DOM to the existing DOM. You first have to compile it with the $compile service on the scope for which you want to use the template. This is because template contain Angular js template syntax. Below is the working snippets.

var myApp = angular.module('myApp', []);

myApp.controller('mainController', ['$scope', function($scope){
   $scope.message = 'Welcome message';
}])

myApp.directive('myTemplate', ['$compile',function($compile) {
  return {
    restrict: 'A',
    scope: true,
    link: function(scope, element, attr) {
    
      var el = $compile('<button ng-click="click()">Click me</button> Clicked {{clicked}} times')(scope);
      element.append(el);

      scope.clicked = 0;
      scope.click = function(){
         scope.clicked++
      }
    }
  }
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="mainController">
    {{message}}
    <div my-template></div>
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download