当我动态更改html时,ng-click in ng-bind-html没有触发

时间:2015-12-14 14:46:03

标签: javascript jquery html angularjs

我创建了一个显示消息的指令,并且它可以呈现任何带有角度属性的html消息,它可能包括按钮,锚标签(带有ng-clicks属性)等等。



的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);
            })
        }
    }
}]);

例如状态为:&#34;点击!&#34;,它呈现完全正常,但ng-click不会触发任何内容。

1 个答案:

答案 0 :(得分:2)

我最终创建了一个动态编译html的新建议here

.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);
            }
        );
    };
}])

并在irErrorPanel.tpl.html中替换

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

使用:

<div compile="status.text"></div>