angularjs中使用ng-bind-html和ng-include

魔豆發表於2016-09-17

下面這個例子,往div標籤內新增html內容:

<!doctype html>
<html ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
  <script type="text/javascript" src="lib/angularjs/angular.min.js" charset="utf-8"></script>
  
</head>
<body ng-controller="ctrl">
    <div ng-bind-html="myText"></div>
<script>
var app = angular.module('myApp',[]);
app.controller("ctrl",function($scope,$sce){
    $scope.myText = $sce.trustAsHtml("<b>粗體內容</b><br/><i>斜體內容</i>");
});
</script>
</body>
</html>

注意在賦值時需要將html用$sce.trustAsHtml作一個處理,不然頁面會報錯,無法輸出內容。

 

下面是ng-include的使用示例,跟上面的例子差不多,只是把要新增的html內容放到一個檔案中:

<!doctype html>
<html ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
  <script type="text/javascript" src="lib/angularjs/angular.min.js" charset="utf-8"></script>
  
</head>
<body ng-controller="ctrl">
    <div ng-include="'demo1_1.html'"></div>
<script>
var app = angular.module('myApp',[]);
app.controller("ctrl",function($scope){});
</script>
</body>
</html>

 

demo1_1.html

<b>粗體內容222</b><br/><i>斜體內容222</i>

相關文章