Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-click in ng-bind-html not firing when i change html dynamically

I created a directive that displays a message, plus it can render any html message with angular attributes maybe, it might include buttons, anchor tags (with ng-clicks attribute) and so on..



index.html:

<ir-error-panel status="status"></ir-error-panel>

irErrorPanel.tpl.html:

<div >
    THE MESSAGE IS:<BR>
    <div ng-bind-html="textHtmlSafe"></div>
    </BR>
</div>

irErrorPanel.js:

angular.module('ng-iridize-common.directives').directive('irErrorPanel', ['$sce', function($sce) {
    return {
        restrict: 'E',
        templateUrl: 'irErrorPanel.tpl.html',
        controller: ['$scope', '$log', function($scope, $log) {

            var _this = this;

            _this.applyMessageText = function applyMessageText() {
                $scope.textHtmlSafe = $scope.status && $scope.status.text ? $sce.trustAsHtml($scope.status.text) : "";
            };

            _this.applyMessageText();

            $scope.$watch("status.text", function(newValue, oldValue) {
                if (newValue === oldValue) {
                    return;
                }
                if (!newValue) {
                    $scope.textHtmlSafe = "";
                    return;
                }
                _this.applyMessageText();

            });


        }],
        link: function(scope, iElement, iAttrs, ctrl) {
            //call service and check box status.
            scope.$watch("status.text", function(value) {
                $compile(iElement.contents())(scope);
            })
        }
    }
}]);

when for example the status is : "click !", it renders perfectly fine, but ng-click doesn't fire anything.

like image 833
Nizar Avatar asked Dec 14 '15 14:12

Nizar


1 Answers

I ended up creating a new directive suggested here that dynamically compiles html.

.directive('compile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },
            function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
}])

and in irErrorPanel.tpl.html replace

<div ng-bind-html="textHtmlSafe"></div>

with:

<div compile="status.text"></div>
like image 119
Nizar Avatar answered Oct 25 '22 22:10

Nizar