3

I've a scenario which I want to run a custom directive on the DOM that ng-bind-htmlcreate.

Basicly I've to customize the behavior of the html tag <a> because the html that is loading is unsafe and when the user click the link I've to execute some functions before anything happens, aka, the click event of jqLite.

So my original ideia was create a directive that modifies the behavior of any <a> inside the container that I put the attribute of my directive.

This works fine, until I combine with ng-bind-html, my directive runs before the ng-bind-html compile the string into html and attached to the DOM.

So, is any way to run my custom directive after the ng-bind-html run?

1 Answers1

2

DEMO

HTML:

<div ng-app="myApp" ng-controller="myCtrl">
       <div ng-bind="sometext" my-directive>before</div>
    </div>

Controller:

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

angular.module('myApp').controller('myCtrl', function($scope) {   
   $scope.sometext="stuff here";
});

Directive:

angular.module('myApp').directive('myDirective', function() { 
        return {
            priority: 10, // adjust this value ;)
            link: function(scope,element,attrs) {
                scope.$watch(attrs.ngBind, function(newvalue) {
                  console.log("element ",element.text());
                });           
            }
        };      
    });

Use priority property inside directive to run your code after mg-bind

mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • Humm.. I didn't think about the `$watch` function.... I made [this](http://jsfiddle.net/az7uukk6/1/) fiddle. Other thing I was thinking about is.. I need take care about unbinding the `click` event on the `$destroy` of the scope? – Rodrigo Cabral Mar 04 '15 at 16:39
  • The Angular documentation for scope destroy, implies that you do need remove DOM events. http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy – mohamedrias Mar 04 '15 at 17:28