【问题标题】:ng-href not working with ng-bind-html [duplicate]ng-href 不适用于 ng-bind-html [重复]
【发布时间】:2017-07-18 20:11:24
【问题描述】:

http://jsfiddle.net/jffnojL1/

这里我有一个简单的 html 元素,我正在尝试使用 ng-bind-html 绑定到 Html。

但这似乎不起作用:

.controller('foo', function($scope) {
    $scope.bar = "<h1>this is bar</h1>";
    $scope.bar1 = "<h1> <a ng-href='www.google.com'> this is bar </a></h1>";
});

<div ng-controller="foo">

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

</div>

如果我使用普通的href,它可以正常工作。谁能解释一下为什么 ng-href 在这种情况下不起作用,或者让我知道如何使它起作用。

【问题讨论】:

  • 大家好......正如我提到的,如果我使用href,它可以正常工作。所以我的问题是为什么 ng-href 不能在这里工作。如何让 ng-href 在这里工作
  • ng-href 在这里不起作用的原因是因为ng-bind-html 没有在绑定的 HTML 中编译任何 ng-* 指令。 href 是要走的路,实际上是 the example in the official docs does here
  • 这不是this post@Sajeetharan的副本

标签: html angularjs


【解决方案1】:

试试这个。因为您在模板中使用了ng,所以您应该编译或删除它。

 $scope.bar1 = "<h1> <a href='www.google.com'> this is bar </a></h1>";

Demo

【讨论】:

    【解决方案2】:

    使用trustAsHtml 来评估安全内容。也使用href insted of ng-href

    angular.module("app",[])
    .controller("ctrl",function($scope,$sce){
    $scope.bar = "<h1>this is bar</h1>";
        $scope.bar1 = "<h1> <a href='www.google.com'> this is bar </a></h1>";
        
        $scope.bar1 = $sce.trustAsHtml($scope.bar1)
    
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="ctrl">
     <div ng-bind-html="bar1"></div>
    </div>

    【讨论】:

      【解决方案3】:

      只需使用href 喜欢

        $scope.bar1 = "<h1> <a href=\"http://www.google.com\"> this is bar </a></h1>";
      

      See Here

      【讨论】:

        猜你喜欢
        • 2014-02-06
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多