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

时间:2017-07-04 06:16:11

标签: angularjs ng-bind-html ng-bind

我想从ng-bind-html中获取数据并将其绑定到其他一些html标签。虽然我可以直接使用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>

2 个答案:

答案 0 :(得分:1)

方式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);
    }
  }
});

方式2:使用AngularJS ng-include

实现
  

你可以直接包含一个html文件:)

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

答案 1 :(得分:0)

使用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>