Kirkland
Kirkland

Reputation: 2533

Is there a callback for ng-bind-html-unsafe in AngularJS

I would like to remove some of the elements that are brought into the DOM by this...

<div ng-bind-html-unsafe="whatever"></div>

I wrote a function that will remove the elements, but I need a way to trigger the function after ng-bind-html-unsafe is complete. Is there a callback for ng-bind-html-unsafe or a better approach?

Upvotes: 2

Views: 1189

Answers (2)

Dalorzo
Dalorzo

Reputation: 20024

I would move the html in your demo to a directive:

<div ng-bind-html-unsafe="whatever"></div>

in the directive I would manipulate the html based on my needs, I am here basing this on an assumption since I am not sure how often or how whatever variable is being updated so the generic solution will be a $watch listener over this variable like this:

$scope.$watch('whatever',function(newValue,oldValue, scope){
     //do something
});

All this code in my new directive, probably you will want to use the postLink function

Here is the Documentation from Angular about this.

Post-linking function Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.

Upvotes: 0

Geoff Genz
Geoff Genz

Reputation: 2119

ng-bind-html-unsafe has been removed from the current version (1.2+) of angular. I would recommend using the $sanitize service in the new version of angular. You'll need to include the sanitize library and add it to your module.

That way you can do whatever you want once the sanitize operation is complete and not worry about a callback.

A quick and dirty implementation:

<!doctype html>
<html lang="en">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.js"></script>
  <script src="libs/angular/angular-sanitize.js"></script>
</head>
<body ng-app="myApp">
  <div ng-controller="myController">
    <div>{{sanitized}}</div>
  </div>
  <script>
    angular.module('myApp', ['ngSanitize'])
      .controller('myController', ['$scope', '$sanitize', function($scope, $sanitize) {
        $scope.sanitized = $sanitize('someTextFromSomeSource');
        // Do whatever you want here with the cleaned up text
      }])
  </script>
</body>
</html> 

Upvotes: 1

Related Questions