значения ng-bind-html для других тегов html

Я хочу взять данные из 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>

person Bhushan Khaladkar    schedule 04.07.2017    source источник


Ответы (2)


Способ 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
person Ramesh Rajendran    schedule 04.07.2017

используйте 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>

person Sachila Ranawaka    schedule 04.07.2017
comment
Я думаю, что ОП запрашивает any other directive for bind to html string - person Ramesh Rajendran; 04.07.2017