AngularJS: Is it possible to post-process ng-bind-html without $ watch?

I have html content to be output by the ng-bind-html directive and after I would like to do some manipulation of that content (like DOM manipulations, jQuery plugins, etc.).

stackoverflow provides me with a solution like this :

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

      

to create a custom directive with a higher priority and look inside:

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

      

and Demo

but since I am not going to change this content, I don’t want to use $ watch . Is it possible to do without $ watch ?

+3


source to share


2 answers


Option 1 (avoid $watch

on demand):

One option is to skip ng-bind-html

and $compile

or $parse

your html yourself. Angular ngBindHtml

itself does something along the lines of:

var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
// ... It does some other, less relevant stuff between these
element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');

      

Angular related source code can be viewed here

This way, you can always write a custom directive that does these things, along with post-processing (even with preprocessing if required). Something like:



var ngBindHtmlGetter = $parse(attrs.someAttrContainingContent);
element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
doPostProcessing(element); // Your additional stuff goes here

      

Option 2 (hold $watch

but untie):

Another option, which might be easier for you, if you want to use ng-bind-html

and are just worried about having an extra observer, you just need to unlock the observer. You can easily unbind it ( $watch

returns the "unbind" function):

var unbindPostProcess = scope.$watch(attrs.ngBind, function(newvalue) {
    doPostProcessing(element); // Whatever the additional function may be
    unbindPostProcess(); // Perhaps guarded to unbind at the right time.
});

      

+1


source


I might misunderstand what you are looking for, but if the question is;

How do I bind HTML to a view without a $ watcher?

this jsBin demonstrates how to do it.

When you upgrade to angular -1.3.x, you get access to one-time bindings {{::expr}}

.



So it really is just a matter of trust to sometext

be both HTML (using $ sce ) and output using ng-bind-html="::sometext"

.

Et voila, no $watchers

, and you can drop the custom directive entirely.


Oh, and if that's not what you want, please tell me and I'll delete my answer.

0


source







All Articles