javascript - 当我动态更改 html 时,ng-bind-html 中的 ng-click 不触发

标签 javascript jquery html angularjs

我创建了一个显示消息的指令,而且它可以呈现任何具有 Angular 属性的 html 消息,它可能包括按钮、 anchor 标记(具有 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);
            })
        }
    }
}]);

例如,当状态为:“点击!”时,它呈现得非常好,但 ng-click 不会触发任何东西。

最佳答案

我最终创建了一个建议的新指令 here动态编译 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);
            }
        );
    };
}])

并在 irErrorPanel.tpl.html 中替换

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

与:

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

关于javascript - 当我动态更改 html 时,ng-bind-html 中的 ng-click 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269836/

相关文章:

javascript - JQuery,当一个输入进入另一个输入(或单击当前输入之外)时如何调用函数?

javascript - 无法更改 div-height vis timeline

javascript - Firebase Web 代码实验室 : missing app configuration value "appId"

javascript - jQuery 拖放

html - 如何将菜单固定在左侧,主要内容固定在右侧

javascript - 使用html和css通过多层创建透明边框

html - 导航的父列表项下的子项

javascript - 无法将输入数据发送到函数并将其作为表返回

Safari 中的 jquery 标签插入问题

javascript - 数组元素的 child