Saturday, September 30, 2017

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  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  times')
},
           controller: function($scope, $element){
             $scope.clicked = 0;
             $scope.click = function(){
               $scope.clicked++
             }
           }
         }
       });

How to attach event here.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/how-to-attach-event-to-dom-created-in-link-function/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment