Prashanth Prashanth - 3 days ago 4
Javascript Question

Angular directive is not compiling after ng-click

The below code is not working after I click on the button. It seems the directive is not compiled again. Can anyone help me out with this !

HTML :

<button ng-click="run()">click</button>
<p>Hello {{name}}!</p>
<customdir filterby="name"></customdir>


The similar code can be found here http://plnkr.co/edit/OQqLeUIoFNhkqSoeIdyM?p=preview.

Javascript :

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

app.controller('MainCtrl', function($scope) {

$scope.name = 'World';

$scope.run = function() {
$scope.name = 'goal';
};

});
app.directive('customdir', function($compile) {
var getTemplate = function(filterby) {
switch (filterby) {
case 'World':
return '<div class="col-lg-1" id="ready">' +
'<img ng-src="http://plnkr.co/img/plunker.png" style="height: 35px; width: 35px; margin-left: 70px; margin-bottom: 3px" />' +
'</div>';
case 'goal':
return '<b>tttttt !!</b>';
default:
return '<b>Error !!</b>';
}
}
return {
restrict: 'E',
scope: {
filterby: '='
},
link: function(scope, element, attrs) {
var el = $compile(getTemplate(scope.filterby))(scope);
element.replaceWith(el);
}
};
});

Answer

You have to use scope.$watch('filterby', function(newValue, oldValue) { }) to handle this on the model change.

Working copy:

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

$scope.run = function() {
$scope.name = 'goal';
};

});


app.directive('customdir', function($compile) {
var getTemplate = function(filterby) {
switch (filterby) {
  case 'World':
    return '<div class="col-lg-1" id="ready">' +
      '<img ng-src="http://plnkr.co/img/plunker.png" style="height: 35px; width: 35px; margin-left: 70px; margin-bottom: 3px" />' +
      '</div>';
  case 'goal':
    return '<b>tttttt !!</b>';
  default:
    return '<b>Error !!</b>';
 }
}
return {
restrict: 'E',
scope: {
  filterby: '='
},
 link: function(scope, element, attrs) {
     
   scope.$watch('filterby', function(newValue, oldValue) {
     var el = $compile(getTemplate(scope.filterby))(scope);
     element.replaceWith(el);
     element = el;
   });
  }
 };
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.5/angular.js" data-semver="1.2.5"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <customdir filterby="name"></customdir>
    <button ng-click="run()">click</button>
  </body>

</html>

Comments