AngularJS: Is it possible to do post-processing of ng-bind-html without $watch? -
i have html content should output ng-bind-html directive, , after manipulations content(for example dom manipulations, jquery plugins, etc).
stackoverflow provides me such solution:
<div ng-app="myapp" ng-controller="myctrl"> <div ng-bind="sometext" my-directive>before</div> </div>
so create custom directive higher priority , watch 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 far i'm not going change content don't want use $watch. possible without $watch?
option 1 (avoid $watch
requested):
one option skip ng-bind-html
, $compile
or $parse
html yourself. angular's ngbindhtml
along lines of:
var ngbindhtmlgetter = $parse(tattrs.ngbindhtml); // ... other, less relevant stuff between these element.html($sce.gettrustedhtml(ngbindhtmlgetter(scope)) || '');
angular's relevant source code can viewed here
so write custom directive things, along post-processing (even pre-processing, if required). along lines of:
var ngbindhtmlgetter = $parse(attrs.someattrcontainingcontent); element.html($sce.gettrustedhtml(ngbindhtmlgetter(scope)) || ''); dopostprocessing(element); // additional stuff goes here
option 2 (keep $watch
, unbind):
another option, may simpler you, if want use ng-bind-html
, you're worried having watcher around, unbind watcher. can unbind quite ($watch
returns "unbind" function):
var unbindpostprocess = scope.$watch(attrs.ngbind, function(newvalue) { dopostprocessing(element); // whatever additional function may unbindpostprocess(); // perhaps guarded unbind @ right time. });
Comments
Post a Comment