javascript - How to watch ng-html-bind from a directive? -
i'm trying watch content of ng-html-bind , modify div content auto link hyperlinks in div since original content not have hyperlink html.
here plunker
here directive
app.directive('autolink', ['$compile', '$timeout', function ($compile, $timeout) { return { restrict: 'ea', replace: true, link: function (scope, element, attrs) { $timeout(function () { var text = element[0].innerhtml; var linktypes = ["http://", "https://"]; linktypes.foreach(function (linktype) { var startspace = 0; while (startspace >= 0) { text = element[0].innerhtml; var locationofhttp = text.indexof(linktype, startspace); if (locationofhttp < 0) break; var locationofspace = text.indexof(" ", locationofhttp); var textafter = ""; if (locationofspace < 0) { locationofspace = text.length; } else { textafter = text.substring(locationofspace, text.length); } var linkurl = text.substring(locationofhttp, locationofspace); var htmltext = text.substring(0, locationofhttp) + '<a href="' + linkurl + '">' + linkurl + '</a>' + textafter; element[0].innerhtml = htmltext; startspace = (text.substring(0, locationofhttp) + '<a href="' + linkurl + '">' + linkurl + '</a>').length - 1; } }); scope.$apply(); console.log("autolink"); }, 1); }, }; }]);
my directive working when page loads not when click on change url, div not auto linking. how watch change , run directive on change ?
so can use scope.$watch() watch change on scope variable, run through link creating function, , add in element.
here fork of plunk that.
i changed ng-bind-html autolink way of using isolate scope (directive isolate scope), allows new text urls in passed directive, scope.$watch takes over. making isolate scope variable same directive name, can use both invoke directive , pass variable it.
the new html:
<div autolink="parseresult(details)"></div>
here code directive below:
app.directive('autolink', ['$compile', '$timeout', function ($compile, $timeout) { return { restrict: 'ea', replace: false, // isolate scope below html attribute // unlinked-text automatically translated // scope variable unlinkedtext angular. scope: { autolink: '=' }, // added template uses ng-bind-html // new, link-ified text template: '<span ng-bind-html="text"></span>', link: function (scope, element, attrs) { scope.text = scope.autolink; function addlinks(str) { var text = str; console.log(text.match(/https?:\/\/\w*/)); var links_parsed = text .replace(/https?:\/\/[\w\.\/]*/g, function(substr) { return '<a href="' + substr + '">' + substr + '</a>'; }); return links_parsed; } // still using timeout initial run of addlinks $timeout(function() { scope.text = addlinks(scope.text); },0) // scope watches autolink variable scope.$watch('autolink', function(newval, oldval) { if(newval !== oldval) { // if variable has changed... scope.text = addlinks(newval); // ...runs addlinks() again } } ); } }; }]);