NG-BIND-HTMLが機能することができません -- html フィールド と angularjs フィールド と ngsanitize フィールド 関連 問題

Not able to get ng-bind-html to work












0
vote

問題

日本語

問題:私はng-bind-htmlを使用しようとしていますが、コンソールで次のエラーが発生しています。

画像の説明を入力します。ここで

次は、NGSANITIZEを呼び出しているコントローラです。

イメージの説明を入力します。ここで

および以下のファイルを使用する:

<事前> <コード> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>

私の形式では、ng-bind-htmlを使用するには、次の手順を実行します。したがって、結果を確認しようとすると、 &amp; を&amp;:

<事前> <コード> <div ng-bind-html="e.Specialty"></div>

と専門分野で発生するものは次のとおりです。

画像の説明を入力しますここで

任意の助けが理解されるでしょう。

@Lealceldeiro:ここに私があなたの提案を実施しようとしているが私がそれを追加する場所がわからないコントローラです:

<事前> <コード> ( function(){ var $scope, $location; var indexApp = angular.module('indexApp',['ui.bootstrap', 'ngSanitize']); indexApp.controller('IndexController',function($scope,$sce,$http,$location,anchorSmoothScroll){ $scope.Lang = 'initVal'; $scope.ShowResults = false; $scope.ShowDesc = true; $scope.NoResults = false; $scope.currentPage = 1; $scope.maxPageNumbersToShow = 10; $scope.formModel = {}; $scope.searchMode = 0; $scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }]; $scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}]; $scope.Gender = [{'value':'Male'},{'value':'Female'}]; $scope.Languages = {}; $scope.Cities = {}; //$scope.lastAction = ''; $scope.searchParam = {}; $("input").removeAttr('disabled'); $scope.searchParam.Distance = $scope.miles[0]; $scope.GetCurrentZip = function (){ try{ var lon, lat; // console.log('starting geoposition code.'); if("geolocation" in navigator){ window.navigator.geolocation.getCurrentPosition(function(pos){ lat = pos.coords.latitude.toFixed(3); lon = pos.coords.longitude.toFixed(3); // console.log(lat + ' ' + lon); $http.get("/Brokers-en-us/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon) .then(function(response){ $scope.searchParam.Zip = response.data; }) }) } else{ console.log('No geolocation'); } } catch(err) { console.log(err.message); } } $scope.GetCityList = function (){ try{ $http.get("/Brokers-en-us/includes/remote/ReturnCityList.cfm") .then(function(response){ $scope.Cities = response.data.Cities; }) } catch(err){} } $scope.GetLangList = function (){ try{ $http.get("/Brokers-en-us/includes/remote/ReturnLangList.cfm") .then(function(response){ $scope.Languages = response.data.Languages; }) } catch(err){} } $scope.SearchProvider = function(searchParam){ try{ //debugger; $scope.searchMode = 1; var queryString=''; if($scope.formModel && $scope.formModel !== searchParam){ $scope.resultsCount = 0; currentPage = 1; } if(searchParam){ //debugger; $scope.formModel = searchParam; for(var param in searchParam){ if(searchParam.hasOwnProperty(param)){ var paramValue = searchParam[param].value ? searchParam[param].value : searchParam[param]; if (paramValue.length > 0) queryString += param + '=' + paramValue + '&'; } } } console.log(queryString); queryString= '?' + queryString + 'currentpage=' + $scope.currentPage; $http.get("/Brokers-en-us/includes/remote/ReturnProvidersList.cfm" + queryString) .then(function(response){ $scope.providers = response.data.provider; $scope.resultsCount = response.data.rowCount; if (!$scope.providers){ $scope.NoResults = true; $scope.ShowResults = false; $scope.ShowDesc = false; } else{ $scope.NoResults = false; $scope.ShowResults = true; $scope.ShowDesc = false; } }) } catch(err){ alert('No response.: ' + err.message); } } /*Testing purposes*/ $scope.clearTopForm = function(searchParam){ //console.log("I clicked this.") } /*Clears the drop downs and input fields*/ $scope.$watch('searchParam.Distance', function(newValue, oldValue) { //debugger; if(newValue != ''){ //$scope.lastAction = 'miles'; $scope.searchParam.City = ''; $scope.searchParam.Specialty = ''; $scope.searchParam.Gender = ''; } }); $scope.$watch('searchParam.Zip', function(newValue, oldValue) { if(newValue != ''){ //$scope.lastAction = 'miles'; $scope.searchParam.Gender = ''; $scope.searchParam.Specialty = ''; $scope.searchParam.City = ''; } }); $scope.cityChange = function(){ //debugger; if($scope.searchParam.City != ''){ //$scope.lastAction = 'city'; $scope.searchParam.Distance = ''; $scope.searchParam.Zip = ''; } } $scope.specialtyChange = function(){ //debugger; if($scope.searchParam.Specialty != ''){ //$scope.lastAction = 'specialty'; $scope.searchParam.Distance = ''; $scope.searchParam.Zip = ''; } } $scope.genderChange = function(){ //debugger; if($scope.searchParam.Gender != ''){ //$scope.lastAction = 'gender'; $scope.searchParam.Distance = ''; $scope.searchParam.Zip = ''; } } $scope.$watchGroup(['currentPage'], function(){ try{ if($scope.searchMode == 1){ $scope.SearchProvider($scope.formModel); } } catch(err){} }); $scope.GetCityList(); $scope.GetLangList(); $scope.GetCurrentZip(); $scope.gotoElement = function (eID){ //http://jsfiddle.net/brettdewoody/y65G5/ // set the location.hash to the id of // the element you wish to scroll to. //$location.hash('bottom'); // call $anchorScroll() var browserWidth = screen.availWidth; if (browserWidth < 768) anchorSmoothScroll.scrollTo(eID); }; }); indexApp.service('anchorSmoothScroll', function(){ this.scrollTo = function(eID) { // This scrolling function // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript var startY = currentYPosition(); var stopY = elmYPosition(eID); var distance = stopY > startY ? stopY - startY : startY - stopY; if (distance < 100) { scrollTo(0, stopY); return; } var speed = Math.round(distance / 100); if (speed >= 20) speed = 20; var step = Math.round(distance / 25); var leapY = stopY > startY ? startY + step : startY - step; var timer = 0; if (stopY > startY) { for ( var i=startY; i<stopY; i+=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY += step; if (leapY > stopY) leapY = stopY; timer++; } return; } for ( var i=startY; i>stopY; i-=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY -= step; if (leapY < stopY) leapY = stopY; timer++; } function currentYPosition() { // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6, 7 and 8 if (document.body.scrollTop) return document.body.scrollTop; return 0; } function elmYPosition(eID) { var elm = document.getElementById(eID); var y = elm.offsetTop; var node = elm; while (node.offsetParent && node.offsetParent != document.body) { node = node.offsetParent; y += node.offsetTop; } return y; } }; }); indexApp.directive('allowPattern',[allowPatternDirective]); indexApp.directive('popPopup',[describePopup]); indexApp.directive('pop', function pop ($tooltip, $timeout) { var tooltip = $tooltip('pop', 'pop', 'event'); var compile = angular.copy(tooltip.compile); tooltip.compile = function (element, attrs) { var first = true; attrs.$observe('popShow', function (val) { if (JSON.parse(!first || val || false)) { $timeout(function(){ element.triggerHandler('event'); }); } first = false; }); return compile(element, attrs); }; return tooltip; }); indexApp.filter('PhoneNumber', function(){ return function(phoneNumber){ var dash = '-'; var openParen = '('; var closeParen = ') '; if(phoneNumber){ var pn = phoneNumber; pn = [pn.slice(0, 6), dash, pn.slice(6)].join(''); pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join(''); return pn; } return phoneNumber; } }); indexApp.filter('Zip', function(){ return function(zipcode){ var dash = '-'; if(zipcode && zipcode.length > 5){ var zc = zipcode; zc = [zc.slice(0, 5), dash, zc.slice(5)].join(''); return zc; } return zipcode; } }); function allowPatternDirective(){ return{ restrict: "A", compile: function(tElement, tAttrs){ return function(scope, element, attrs){ element.bind("keypress", function(event){ var keyCode = event.which || event.keyCode; var keyCodeChar = String.fromCharCode(keyCode); if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){ event.preventDefault(); return false; } }); } } } } function describePopup(){ return { restrict: 'EA', replace: true, scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/popover/popover.html' }; } })(); (function($) { // @todo Document this. $.extend($,{ placeholder: { browser_supported: function() { return this._supported !== undefined ? this._supported : ( this._supported = !!('placeholder' in $('<input type="text">')[0]) ); }, shim: function(opts) { var config = { color: '#888', cls: 'placeholder', selector: 'input[placeholder], textarea[placeholder]' }; $.extend(config,opts); return !this.browser_supported() && $(config.selector)._placeholder_shim(config); } }}); $.extend($.fn,{ _placeholder_shim: function(config) { function calcPositionCss(target) { var op = $(target).offsetParent().offset(); var ot = $(target).offset(); return { top: ot.top - op.top, left: ot.left - op.left, width: $(target).width() }; } function adjustToResizing(label) { var $target = label.data('target'); if(typeof $target !== "undefined") { label.css(calcPositionCss($target)); $(window).one("resize", function () { adjustToResizing(label); }); } } return this.each(function() { var $this = $(this); if( $this.is(':visible') ) { if( $this.data('placeholder') ) { var $ol = $this.data('placeholder'); $ol.css(calcPositionCss($this)); return true; } var possible_line_height = {}; if( !$this.is('textarea') && $this.css('height') != 'auto') { possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' }; } var isBorderBox = ($this.css('box-sizing') === 'border-box'); var isTextarea = $this.is('textarea'); var ol = $('<label />') .text($this.attr('placeholder')) .addClass(config.cls) .css($.extend({ position:'absolute', display: 'inline', 'float':'none', overflow:'hidden', textAlign: 'left', color: config.color, cursor: 'text', paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'), paddingRight: $this.css('padding-right'), paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'), paddingLeft: $this.css('padding-left'), fontSize: $this.css('font-size'), fontFamily: $this.css('font-family'), fontStyle: $this.css('font-style'), fontWeight: $this.css('font-weight'), textTransform: $this.css('text-transform'), backgroundColor: 'transparent', zIndex: 99, }, possible_line_height)) .css(calcPositionCss(this)) .attr('for', this.id) .data('target',$this) .click(function(){ if (!$(this).data('target').is(':disabled')) { $(this).data('target').focus(); } }) .insertBefore(this); $this .data('placeholder', ol) .on('keydown', function () { ol.hide(); }) .on('blur change', function () { ol[$this.val().length ? 'hide' : 'show'](); }) .triggerHandler('blur'); $(window).one("resize", function () { adjustToResizing(ol); }); } }); } }); })(jQuery); jQuery(document).add(window).bind('ready load', function() { if (jQuery.placeholder) { jQuery.placeholder.shim(); } });
英語

Problem: I am trying to use ng-bind-html but I am getting the following errors on the console:

enter image description here

The following is the controller where I am calling ngSanitize:

enter image description here

and using the following file:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script> 

In my form, I do the following to use ng-bind-html. So when I try to see my results, it is still rendering the &amp;rather then &:

<div ng-bind-html="e.Specialty"></div> 

and the following is what occurs in the Specialty:

enter image description here

Any help would be appreciated.

@lealceldeiro: Here is the controller in which I am trying to implement your suggestion but not sure where I will add it:

( function(){     var $scope, $location;     var indexApp = angular.module('indexApp',['ui.bootstrap', 'ngSanitize']);      indexApp.controller('IndexController',function($scope,$sce,$http,$location,anchorSmoothScroll){         $scope.Lang = 'initVal';         $scope.ShowResults = false;         $scope.ShowDesc = true;         $scope.NoResults = false;         $scope.currentPage = 1;         $scope.maxPageNumbersToShow = 10;         $scope.formModel = {};         $scope.searchMode = 0;         $scope.miles =  [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];         $scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}];         $scope.Gender = [{'value':'Male'},{'value':'Female'}];         $scope.Languages = {};         $scope.Cities = {};         //$scope.lastAction = '';         $scope.searchParam = {};         $("input").removeAttr('disabled');          $scope.searchParam.Distance = $scope.miles[0];          $scope.GetCurrentZip = function (){             try{                 var lon, lat;                 // console.log('starting geoposition code.');                 if("geolocation" in navigator){                     window.navigator.geolocation.getCurrentPosition(function(pos){                         lat = pos.coords.latitude.toFixed(3);                         lon = pos.coords.longitude.toFixed(3);                         // console.log(lat + ' ' + lon);                         $http.get("/Brokers-en-us/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)                         .then(function(response){                             $scope.searchParam.Zip = response.data;                         })                     })                 }                 else{ console.log('No geolocation'); }             }             catch(err) { console.log(err.message); }         }          $scope.GetCityList = function (){             try{                 $http.get("/Brokers-en-us/includes/remote/ReturnCityList.cfm")                     .then(function(response){                         $scope.Cities = response.data.Cities;                     })             }             catch(err){}         }          $scope.GetLangList = function (){             try{                 $http.get("/Brokers-en-us/includes/remote/ReturnLangList.cfm")                     .then(function(response){                         $scope.Languages = response.data.Languages;                     })             }             catch(err){}         }          $scope.SearchProvider = function(searchParam){             try{                 //debugger;                 $scope.searchMode = 1;                 var queryString='';                 if($scope.formModel && $scope.formModel !== searchParam){                     $scope.resultsCount = 0;                     currentPage = 1;                 }                 if(searchParam){                     //debugger;                     $scope.formModel = searchParam;                     for(var param in searchParam){                         if(searchParam.hasOwnProperty(param)){                             var paramValue = searchParam[param].value ? searchParam[param].value : searchParam[param];                             if (paramValue.length > 0)                                 queryString += param + '=' + paramValue + '&';                         }                     }                 }                 console.log(queryString);                 queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;                  $http.get("/Brokers-en-us/includes/remote/ReturnProvidersList.cfm" + queryString)                 .then(function(response){                     $scope.providers = response.data.provider;                     $scope.resultsCount = response.data.rowCount;                     if (!$scope.providers){                             $scope.NoResults = true;                             $scope.ShowResults = false;                             $scope.ShowDesc = false;                         }                     else{                             $scope.NoResults = false;                             $scope.ShowResults = true;                             $scope.ShowDesc = false;                         }                 })             }             catch(err){ alert('No response.: ' + err.message); }         }          /*Testing purposes*/         $scope.clearTopForm = function(searchParam){             //console.log("I clicked this.")         }          /*Clears the drop downs and input fields*/         $scope.$watch('searchParam.Distance', function(newValue, oldValue) {             //debugger;                     if(newValue != ''){                         //$scope.lastAction = 'miles';                         $scope.searchParam.City = '';                         $scope.searchParam.Specialty = '';                         $scope.searchParam.Gender = '';                     }         });          $scope.$watch('searchParam.Zip', function(newValue, oldValue) {                     if(newValue != ''){                         //$scope.lastAction = 'miles';                         $scope.searchParam.Gender = '';                         $scope.searchParam.Specialty = '';                         $scope.searchParam.City = '';                     }         });          $scope.cityChange = function(){             //debugger;             if($scope.searchParam.City != ''){                 //$scope.lastAction = 'city';                 $scope.searchParam.Distance = '';                 $scope.searchParam.Zip = '';             }         }          $scope.specialtyChange = function(){             //debugger;             if($scope.searchParam.Specialty != ''){                 //$scope.lastAction = 'specialty';                 $scope.searchParam.Distance = '';                 $scope.searchParam.Zip = '';             }         }          $scope.genderChange = function(){             //debugger;             if($scope.searchParam.Gender != ''){                 //$scope.lastAction = 'gender';                 $scope.searchParam.Distance = '';                 $scope.searchParam.Zip = '';             }         }          $scope.$watchGroup(['currentPage'], function(){             try{                 if($scope.searchMode == 1){                     $scope.SearchProvider($scope.formModel);                     }             }             catch(err){}         });           $scope.GetCityList();         $scope.GetLangList();         $scope.GetCurrentZip();          $scope.gotoElement = function (eID){             //http://jsfiddle.net/brettdewoody/y65G5/               // set the location.hash to the id of               // the element you wish to scroll to.              //$location.hash('bottom');                // call $anchorScroll()             var browserWidth = screen.availWidth;             if (browserWidth < 768)                 anchorSmoothScroll.scrollTo(eID);         };      });      indexApp.service('anchorSmoothScroll', function(){         this.scrollTo = function(eID) {              // This scrolling function              // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript              var startY = currentYPosition();             var stopY = elmYPosition(eID);             var distance = stopY > startY ? stopY - startY : startY - stopY;             if (distance < 100) {                 scrollTo(0, stopY); return;             }             var speed = Math.round(distance / 100);             if (speed >= 20) speed = 20;             var step = Math.round(distance / 25);             var leapY = stopY > startY ? startY + step : startY - step;             var timer = 0;             if (stopY > startY) {                 for ( var i=startY; i<stopY; i+=step ) {                     setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);                     leapY += step; if (leapY > stopY) leapY = stopY; timer++;                 } return;             }             for ( var i=startY; i>stopY; i-=step ) {                 setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);                 leapY -= step; if (leapY < stopY) leapY = stopY; timer++;             }              function currentYPosition() {                 // Firefox, Chrome, Opera, Safari                 if (self.pageYOffset) return self.pageYOffset;                 // Internet Explorer 6 - standards mode                 if (document.documentElement && document.documentElement.scrollTop)                     return document.documentElement.scrollTop;                 // Internet Explorer 6, 7 and 8                 if (document.body.scrollTop) return document.body.scrollTop;                 return 0;             }              function elmYPosition(eID) {                 var elm = document.getElementById(eID);                 var y = elm.offsetTop;                 var node = elm;                 while (node.offsetParent && node.offsetParent != document.body) {                     node = node.offsetParent;                     y += node.offsetTop;                 } return y;             }          };      });      indexApp.directive('allowPattern',[allowPatternDirective]);     indexApp.directive('popPopup',[describePopup]);     indexApp.directive('pop', function pop ($tooltip, $timeout) {     var tooltip = $tooltip('pop', 'pop', 'event');     var compile = angular.copy(tooltip.compile);     tooltip.compile = function (element, attrs) {             var first = true;       attrs.$observe('popShow', function (val) {         if (JSON.parse(!first || val || false)) {             $timeout(function(){                 element.triggerHandler('event');             });             }             first = false;         });         return compile(element, attrs);         };         return tooltip;     });      indexApp.filter('PhoneNumber', function(){     return function(phoneNumber){         var dash = '-';         var openParen = '(';         var closeParen = ') ';         if(phoneNumber){             var pn = phoneNumber;             pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');             pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join('');             return pn;             }         return phoneNumber;         }     });      indexApp.filter('Zip', function(){     return function(zipcode){         var dash = '-';         if(zipcode && zipcode.length > 5){             var zc = zipcode;             zc = [zc.slice(0, 5), dash, zc.slice(5)].join('');             return zc;             }         return zipcode;         }     });      function allowPatternDirective(){         return{             restrict: "A",             compile: function(tElement, tAttrs){                 return function(scope, element, attrs){                     element.bind("keypress", function(event){                         var keyCode = event.which || event.keyCode;                         var keyCodeChar = String.fromCharCode(keyCode);                          if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){                             event.preventDefault();                             return false;                         }                     });                 }             }         }     }      function describePopup(){         return {             restrict: 'EA',             replace: true,             scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' },             templateUrl: 'template/popover/popover.html'             };         } })(); (function($) {   // @todo Document this.   $.extend($,{ placeholder: {       browser_supported: function() {         return this._supported !== undefined ?           this._supported :           ( this._supported = !!('placeholder' in $('<input type="text">')[0]) );       },       shim: function(opts) {         var config = {           color: '#888',           cls: 'placeholder',           selector: 'input[placeholder], textarea[placeholder]'         };         $.extend(config,opts);         return !this.browser_supported() && $(config.selector)._placeholder_shim(config);       }   }});    $.extend($.fn,{     _placeholder_shim: function(config) {       function calcPositionCss(target)       {         var op = $(target).offsetParent().offset();         var ot = $(target).offset();          return {           top: ot.top - op.top,           left: ot.left - op.left,           width: $(target).width()         };       }       function adjustToResizing(label) {         var $target = label.data('target');         if(typeof $target !== "undefined") {           label.css(calcPositionCss($target));           $(window).one("resize", function () { adjustToResizing(label); });         }       }       return this.each(function() {         var $this = $(this);          if( $this.is(':visible') ) {            if( $this.data('placeholder') ) {             var $ol = $this.data('placeholder');             $ol.css(calcPositionCss($this));             return true;           }            var possible_line_height = {};           if( !$this.is('textarea') && $this.css('height') != 'auto') {             possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' };           }            var isBorderBox = ($this.css('box-sizing') === 'border-box');           var isTextarea = $this.is('textarea');            var ol = $('<label />')             .text($this.attr('placeholder'))             .addClass(config.cls)             .css($.extend({               position:'absolute',               display: 'inline',               'float':'none',               overflow:'hidden',               textAlign: 'left',               color: config.color,               cursor: 'text',               paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'),               paddingRight: $this.css('padding-right'),               paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'),               paddingLeft: $this.css('padding-left'),               fontSize: $this.css('font-size'),               fontFamily: $this.css('font-family'),               fontStyle: $this.css('font-style'),               fontWeight: $this.css('font-weight'),               textTransform: $this.css('text-transform'),               backgroundColor: 'transparent',               zIndex: 99,             }, possible_line_height))             .css(calcPositionCss(this))             .attr('for', this.id)             .data('target',$this)             .click(function(){                 if (!$(this).data('target').is(':disabled')) {                     $(this).data('target').focus();                 }             })             .insertBefore(this);             $this                 .data('placeholder', ol)                 .on('keydown', function () {                     ol.hide();                 })                 .on('blur change', function () {                     ol[$this.val().length ? 'hide' : 'show']();                 })                 .triggerHandler('blur');           $(window).one("resize", function () { adjustToResizing(ol); });         }       });     }   }); })(jQuery);  jQuery(document).add(window).bind('ready load', function() {   if (jQuery.placeholder) {     jQuery.placeholder.shim();   } }); 
</div
        
         
         

回答リスト

3
 
vote
vote
ベストアンサー
 

NG-BIND-HTML を使用すると、Angularjsは時々検討することがあります内容が安全でない(あなたのケースとして)、(下のデモを参照)

$ sanitize

入力は、HTMLをトークンに解析することによって消毒されます。すべての金庫 トークン(ホワイトリストから)は、適切にエスケープされるようにシリアル化されます。 HTML文字列これは、安全でない入力がそれをすることができることを意味します

この場合、 "Unsafe"の部分は &amp;

です。

 <コード> angular  .module('app', [])  .controller('ctrl', ctrl);    function ctrl($scope, $sce) {  $scope.Specialty = $sce.trustAsHtml("CLINICAL &amp; SOCIAL");  }  
 <コード> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>    <div ng-app="app" ng-controller="ctrl">    Specialty: <span ng-bind-html="Specialty"></span>    </div>  
 

When you use ng-bind-html, AngularJS sometimes consider some contents as unsafe (as your case), so you need to use the $sce service in order to "mark" this content as safe (to be used) like this:

$sce.trustAsHtml("CLINICAL &amp; SOCIAL"); (See demo below)

From $sanitize

The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are then serialized back to properly escaped html string. This means that no unsafe input can make it into the returned string.

In this case the "unsafe" part is &amp;

angular  .module('app', [])  .controller('ctrl', ctrl);    function ctrl($scope, $sce) {  $scope.Specialty = $sce.trustAsHtml("CLINICAL &amp; SOCIAL");  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>    <div ng-app="app" ng-controller="ctrl">    Specialty: <span ng-bind-html="Specialty"></span>    </div>
</div
 
 
   
   

関連する質問

3  angularjs ngsanitizeエラー  ( Angularjs ngsanitize error ) 
こんにちはこんにちはそれは私の最初の質問です。私は多くのフォーラムで検索しましたが、私の問題に対する解決策を見つけませんでした!あなたがみんな私を助けることができることを願っています! 問題:NGSANITIZEモジュールを使用する必要がありますが、プロジェク...

0  NG-BIND-HTMLが機能することができません  ( Not able to get ng bind html to work ) 
問題:私はng-bind-htmlを使用しようとしていますが、コンソールで次のエラーが発生しています。 次は、NGSANITIZEを呼び出しているコントローラです。 および以下のファイルを使用する: <事前> <コード> <script src=...

1  PREおよびPOSTマークアップとしてNG-BIND-HTMLでNGリピート  ( Ng repeat with ng bind html as pre and post markup ) 
私はこれと同様に、複数のオブジェクトを持つ配列を持っています: <事前> <コード> FirebaseOptions options = new FirebaseOptions.Builder() .setCr...

1  AngularyJS Cordovaアプリで外部リンクを開きます  ( Angularjs open external links in an cordova app ) 
外部リンクを開こうとしているCordovaアプリでNG-BIND-HTMLを使用する。 私はinAppBrowserプラグインをインストールしています それから私は以下のステップからの正確なステップに従った。 https://gist.githu...

0  ngsanitize:<スタイル> <! - n - > </ style>には、悪い解析エラーangularjsが与えられます。  ( Ngsanitize badparse for style n style gives bad parse error angul ) 
サニタイズしようとしているバッドパースエラーを得ます <コード> <style> <!-- --> </style> は、不良解析エラーangularjsを与えます。私のモジュールでNGSanitizeを使用して消毒します。私はほとんどのHTMLコンテンツを...

0  Angular.js 1.4 $インジェクタ:私のアプリでngsanitizeを含めることを試みるときのモジュールエラー  ( Angular js 1 4 injectormodule error when trying to include ngsanitize in my ap ) 
私はオンラインで、そしてこのサイトで解決策を見てきましたが、私のコントローラに 'ngsanitize'を追加するときになぜ私のアプリでinjector-moduleエラーを取得しました。 https://jsfiddle.net/mxmqxos7/2/ ...

51  Angular Sanitize / NG-BIND-HTMLが機能していませんか?  ( Angular sanitize ng bind html not working ) 
リピーターを設定し、それにHTMLがない限りデータを表示することができます。 angular-sanitize.js を含め、 ng-bind-html を使用してみました。 しかし、 ng-bind-html 属性内でのみスパン内に表示されません。それ...

2  HTML文字エンティティを持つANGULARJS NG-BIND-HTML  ( Angularjs ng bind html with html character entities ) 
<事前> <コード> var text1 = "<b>sometext</b>"; var text2 = "&lt;b&gt;sometext&lt;/b&gt;"; <コード> ng-bind-html="text1" はうまく機能します。...

0  HTMLの電子メールの内容の角度消毒化装置と孤立山脈ブラケット  ( Angular sanitizer and orphan angle bracket in html email content ) 
私の角度アプリでは、Angular Sanitizationを適用しましたので、無効なHTMLが(GetTrustedHTML Mathodを使用)、有効なHTMLがWeb APIに(HTTPPOST)になる(HTTPPOST)。また、Web APIのHTML...

2  サーバー側のScala / Javaでの角度$ SANITIZEと同等  ( Equivalent to angular sanitize in scala java on the server side ) 
角度のような文字列を消毒する: <事前> <コード> var sanitized = $sanitize($scope.someHtml); アプリケーション画面でMaligh HTML / JavaScriptに入力しようとするとうまく機能します。 しか...




© 2022 cndgn.com All Rights Reserved. Q&Aハウス 全著作権所有