write renderizar example javascript angularjs binding ng-bind-html

javascript - example - renderizar html angularjs



Angularjs ng-bind-html-reemplazo inseguro (4)

Solía ​​ser capaz de usar ng-bind-html-unsafe para generar código no mejorado (porque la desinfección se produce en el servidor).

Pero ahora esa opción se ha ido? Sé que puedo usar $sce.trustAsHtml pero agregar eso al JavaScript en todas partes es un gran dolor cuando inseguro es tan fácil de usar.

¿Cómo me vuelvo inseguro?


Bueno, es bastante simple crear tu propia directiva, aquí hay un ejemplo.

Directiva :

app.directive(''bindHtmlUnsafe'', function( $compile ) { return function( $scope, $element, $attrs ) { var compile = function( newHTML ) { // Create re-useable compile function newHTML = $compile(newHTML)($scope); // Compile html $element.html('''').append(newHTML); // Clear and append it }; var htmlName = $attrs.bindHtmlUnsafe; // Get the name of the variable // Where the HTML is stored $scope.$watch(htmlName, function( newHTML ) { // Watch for changes to // the HTML if(!newHTML) return; compile(newHTML); // Compile it }); }; });

Uso :

<div bind-html-unsafe="testHTML"></div>

Demostración: http://jsfiddle.net/cC5VZ/2


La manera más simple, sin $ sce:

module.directive(''html'', function() { function link(scope, element, attrs) { var update = function() { element.html(scope.html); } attrs.$observe(''html'', function(value) { update(); }); } return { link: link, scope: { html: ''='' } }; });

Cómo utilizar:

<div html="angular.variable"></div>


Simpler de nuevo.

App.filter(''unsafe'', [''$sce'', function ($sce) { return function (val) { return $sce.trustAsHtml(val); }; }]);

Uso:

<any ng-bind-html="content | unsafe"></any>

Para obtener más información sobre el enlace html, consulte los documentos aquí.

Solo una advertencia: asegúrese de que realmente confía en el html, o podría estar abriendo un agujero en la seguridad de su sitio.


Recomiendo consultar este ejemplo de SIMPLE JSFiddle. Fue un salvavidas:

http://jsfiddle.net/cC5VZ/2/

<div ng-app="ngBindHtmlExample"> <div ng-controller="ngBindHtmlCtrl"> <p ng-bind-html="myHTML" compile-template></p> </div> </div> var app = angular.module(''app'', []); app.controller(''testApp'', function( $scope ) { $scope.testHTML = ''<h1> Welcome :) </h1>''; }); app.directive(''bindHtmlUnsafe'', function( $parse, $compile ) { return function( $scope, $element, $attrs ) { var compile = function( newHTML ) { newHTML = $compile(newHTML)($scope); $element.html('''').append(newHTML); }; var htmlName = $attrs.bindHtmlUnsafe; $scope.$watch(htmlName, function( newHTML ) { if(!newHTML) return; compile(newHTML); }); }; });