Search code examples
javascriptjqueryangularjsdirective2-way-object-databinding

Adding a class to a trustedValue AngularJS


I have the following html:

<li class="editor" ng-model="post.text" ng-bind-html="post.text" add-class="post.text"></li>

where post.text is a wrapped trustedValue, that looks like this:

http://i.imgur.com/ZrcqGHR.png

after I unwrap it, it looks like this:

http://i.imgur.com/LJBeArp.png

Now, I want to make a directive, that searches that trustedValue, and adds a class to the img tags. So far I have this:

function AddClassToImg($sce) {
    return {
        restrict: 'A',
        scope: {
            addClass: '='
        },
        link: function (scope, elem, attrs) {
            var content = scope.addClass.$$unwrapTrustedValue();
            $(content).find('img').addClass('test');
        }
    }
};

angular.module('UserProfile')
    .directive('addClass', ['$sce', AddClassToImg]);

How can I get the post.text from the html, two-way-bind to it, and add to all images in post.text that class?


Solution

  • I solved it, for everyone wondering the same thing, here is the code:

    function AddClassToImg($sce, $compile){
        return {
            restrict: 'A',
            scope:{
                addClass: '='
            },
            link: function (scope, elem, attrs){
    
                var content = scope.addClass.$$unwrapTrustedValue();
                var newContent = $("<div>").append($(content).find('img').addClass('col-md-12 col-xs-12').end()).html();
                scope.addClass = $sce.trustAsHtml(newContent);
            }
        }
    };