Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular - Listening on transcluded change

I have a simple directive

angular.module('myApp')
    .directive('myDirective', function () {
        return {
            template: '<p ng-transclude></p>',
            restrict: 'A',
            transclude: true,
            link: function postLink(scope, element, attrs) {
            }
        }
    }
);

I am trying to run code each time the transclusion content changes and the directive is rendered - I need the transcluded content.

Example algorithm I would like to run in this case is:

  • count words of transcluded content.

I have tried scope.$watch in multiple forms but to no avail.

like image 464
guy mograbi Avatar asked Oct 21 '13 08:10

guy mograbi


1 Answers

We can use the jqlite included within Angular inside a watch expression function to accomplish this. Below is code that watches the length of the transcluded element using jqLite (element.text().length). The watch fires whenever the length of the element that this directive is attached to changes.

And the new length is passed in as newValue to the second function within the watch (since we return it from the first watch function).

  myApp.directive('myDirective', function () {
     return {
        template: '<p ng-transclude></p>',
        restrict: 'A',
        transclude: true,
        replace: true,
        link: function (scope, element, attrs) {

           scope.$watch(function () {
               return element.text().length;
           },

           function (newValue, oldValue) {
               console.log('New Length ', newValue);
          });
        }
      }
  });

I've got a working jsfiddle here:

http://jsfiddle.net/2erbF/6/

This addresses the word/letter count scenario. But you could write a test on the element.text() itself if you needed it to fire on any changes- not just a length change.

like image 100
KayakDave Avatar answered Nov 06 '22 12:11

KayakDave