ng-bind-html 值到其他 html 标签

ng-bind-html values to other html tags

我想从 ng-bind-html 获取数据并将其绑定到其他 html tags.Though 我可以直接使用 ng-bind-html它。但是有没有其他方法可以将绑定的 html 用于其他 HTML 标签?

JS:

 $scope.left = '<span>Hello World</span><strong>New Testing<strong><br/>h1>Testing</h1>';

HTML:

<div ng-bind-html="left" ng-model="GetValues"></div>

<span>{{GetValues}}</span>

使用trustAsHtml将字符串编译成Dom

$scope.trustAsHtml = function(html){
   return $sce.trustAsHtml(html);
}

现在调用html

中的函数
<div ng-bind-html="trustAsHtml(left)" ng-model="GetValues"></div>

angular.module("app",[])
.controller("ctrl",function($scope,$sce){
 $scope.left = '<span>Hello World</span><strong>New Testing<strong><br/><h1>Testing</h1>';

  $scope.trustAsHtml = function(html){
    return $sce.trustAsHtml(html);
  }
})
<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="trustAsHtml(left)" ng-model="GetValues"></div>

<span>{{GetValues}}</span>
</div>

方式 1:使用 $compile

实现

html

<div my-directive="left" ng-model="GetValues"></div>

指令

var app = angular.module('myApp',[]);
app.controller('ctrlMain',function($scope){
    $scope.bindMe = {id:1,myvar:"test"};
});
app.directive('myDirective', function($compile){
  return{
    restrict: 'A',
    scope: {
        varToBind: '=myDirective'     
    },
    link: function(scope, elm, attrs){
      outerList = '<span>Hello World</span><strong>New Testing<strong><br/>h1>Testing</h1>';
      outerList = $compile(outerList)(scope);
      elm.replaceWith(outerList);
    }
  }
});

方式二:使用AngularJS ng-include

实现

you can directly include a html file :)

<div ng-include="'myFile.htm'"></div>//your DOM string code should be in myfile.htm file