ng-click not working on newly appended elements

2.8k views Asked by At

Why is my ng-click not working when I appended it with a button? The same ng-click is working when I initially loaded the button.

app.controller('demoCtrl', function() {


          this.clk = '<button ng-click="dctrl.click()">Button</button>';

          this.click = function() {

            alert('clicked');

          }
})

 app.directive('btnClick', function() {

          return {

            restrict: 'A',
            scope: {

              actionBtn: '='

            },
            link: function(scope, element, attrs) {

              element.append(scope.actionBtn);

            }

          }

})

HTML

<body ng-controller="demoCtrl as dctrl">

        <div btn-click action-btn="dctrl.clk"></div>

</body>

http://plnkr.co/edit/QPKXfGd9s7HzLvEfKvbG?p=preview

Update

I've also tried this way but no luck

element.append($compile(scope.actionBtn)(scope));
1

There are 1 answers

4
Arun P Johny On

You need to compile an new dom element created manually for angularjs to work on it so

app.directive('btnClick', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.append($compile(scope.$eval(attrs.actionBtn))(scope));
        }
    }
}])

var app = angular.module('my-app', [], function() {})

app.controller('demoCtrl', function() {
  this.clk = '<button ng-click="dctrl.click()">Button</button>';

  this.click = function() {
    alert('clicked');
  }
})

app.directive('btnClick', ['$compile',
  function($compile) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        element.append($compile(scope.$eval(attrs.actionBtn))(scope));
      }
    }
  }
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="demoCtrl as dctrl">
  <div action-btn="dctrl.clk" btn-click></div>
</div>