2017-07-18 94 views
0

http://jsfiddle.net/jffnojL1/NG-HREF不NG綁定,HTML

在這裏,我有我正努力用NG綁定,HTML綁定到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不能在這種情況下工作,或讓我知道如何使這項工作。

+0

大家好..正如我前面提到它工作正常,如果我使用的href 。所以我的問題是爲什麼ng-href不在這裏工作。如何讓ng-href在這裏工作 – undefined

+1

'ng-href'在這裏不起作用的原因是因爲'ng-bind-html'不會在綁定的HTML內編譯任何'ng- *'指令。 'href'是要走的路,實際上是[官方文檔中的例子](https://docs.angularjs.org/api/ng/directive/ngBindHtml)。 –

+1

這不是[此帖子]的重複(https://stackoverflow.com/q/43317123/6712896)@Sajeetharan – JeanJacques

回答

0

試試用這個。因爲您在模板中使用ng,所以您應該編譯它或將其刪除。

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

Demo

0

爲了evaluete安全內容使用trustAsHtml。還使用href insted的的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>

0

只需使用href

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

See Here