【问题标题】:ng-click in ng-bind-html not firing when i change html dynamically当我动态更改html时,ng-bind-html中的ng-click不会触发
【发布时间】:2015-12-14 23:06:54
【问题描述】:

我创建了一个显示消息的指令,另外它可以渲染任何带有角度属性的 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);
            })
        }
    }
}]);

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

【问题讨论】:

    标签: javascript jquery html angularjs


    【解决方案1】:

    我最终创建了一个建议 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>
    

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 2014-07-16
      • 2014-11-12
      • 2014-12-28
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2016-05-29
      相关资源
      最近更新 更多