簡體   English   中英

使用ng-bind-html,角度ng-show / ng-hide無法正常工作

[英]angular ng-show / ng-hide not working correctly with ng-bind-html

我想為html字符串中的元素設置ng-show或ng-hide,並使用ng-bind-html將其傳遞給視圖但ng-show / ng-hide不起作用且我的元素始終可見。

這是我的控制器代碼:

  $scope.my = {
    messageTrue: true,
    messageFalse: false
  };

  $scope.HtmlContent = "<div ng-show='{{my.messageFalse}}'>This is incorrect (ng-show & my.messageFalse={{my.messageFalse}})</div> ";
  $scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);

這是我的查看代碼:

<div ng-show="my.messageTrue">This is correct (ng-show & my.messageTrue={{my.messageTrue}})</div>
<div ng-hide="my.messageFalse">This is correct (ng-hide & my.messageFalse={{my.messageFalse}})</div>
<div ng-bind-html="trustedHtml"></div>

對於我的問題, 這是一個Plnkr (感謝Xaero

對不起,我的英語不好。 謝謝

這是因為您注入的html尚未按角度編譯和鏈接,因此它只是“按原樣”顯示。 如果你根本沒有包含angular.js,它的處理方式與你的標記處理方式相同。

解決方案是創建一個類似於ng-bind-html的指令,但它還包括編譯和鏈接html片段的步驟。

此鏈接是此類指令的示例。

這是代碼:

angular.module('ngHtmlCompile', []).
    directive('ngHtmlCompile', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$watch(attrs.ngHtmlCompile, function(newValue, oldValue) {
                element.html(newValue);
                $compile(element.contents())(scope);
            });
        }
    }
});

和用法。

<div ng-html-compile="trustedHtml"></div> 

這是工作的普朗克

您是否在控制器中注入了$ interpolate,並在模塊中添加了ngSanitize?

這是一個有效的plnkr: http ://plnkr.co/edit/qTsUzi04tCNdK5BAZvDa?p = preview

// controller.js
var app = angular.module('app');

app.controller('indexController', indexController);

function indexController($scope, $interpolate) {
  $scope.my = {
    messageTrue: true,
    messageFalse: false
  };

  $scope.HtmlContent = "<div ng-show='{{my.messageTrue}}'>{{my.messageTrue}}</div> ";
  $scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);
}

// app.js
angular.module('app', ['ngSanitize']);

// index.html
<!DOCTYPE html>
<html>
<head></head>

<body ng-app="app" ng-controller="indexController">
<div ng-show="my.messageTrue">{{my.messageTrue}}</div>
<div ng-show="my.messageFalse">{{1 + 1}}</div>

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

<script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-sanitize.js"></script>
<script src="app.js"></script>
<script src="controller.js"></script>
</body>
</html>

和使用ng-bind-html的這個鏈接: 如何通過AngularJS模板輸出html?

$scope.my = { message: false };
$scope.HtmlContent = "<div ng-show='{{my.message}}'>{{my.message}}</div> ";
$scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);

你應該試試這個:

<div ng-show="my.message == false">{{my.message}}</div> 
<div ng-bind-html="trustedHtml"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM