如何在HTML实体上使用Sanitize [英] How to use Sanitize on HTML Entity

查看:73
本文介绍了如何在HTML实体上使用Sanitize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我希望能够解码Angular表达式中的HTML实体.根据在线阅读的内容,我可以使用Sanitize和ng-bind-html.

Problem: I would like to be able to decode an HTML entity in an Angular expression. Based on what I have read online, I can use Sanitize and ng-bind-html.

但是,基于我在网上看到的示例(如下):

However, based on the examples I have seen online (below):

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

<div ng-app="myApp" ng-controller="myCtrl">

<p ng-bind-html="myText"></p>

</div>

<script>
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "My name is: &John Doe&";
});
</script>

我不确定如何应用以下角度表达式查找的内容:

I am not sure how I can apply what I have looked up with the following angular expression:

<div id="searchResults" ng-repeat="e in Data" ng-show="ShowResults">
  <div class="row">
    <div class="col-md-4 no-margin padding">
       <strong>Data:</strong> {{e.Specialty}}
    </div>
 </div>
</div>

更新:我尝试了以下操作,当显示结果时,专业"显示为空白,并且在调试代码时,看来采用这种方法会删除它

Update: I have tried the following and when I display results, the Specialty appears blank and when I debug code, it appears that doing that approach removes it

  <strong>Data:</strong> <span ng-bind-html="e.Specialty"></span>

这里是我称之为专业的angularjs.我将在哪里包括"ngSanitize".但是,当我包含ngSanitize并不确定为什么这样做时,它将使表单中的所有内容崩溃

Here is the angularjs where I am calling the specialty. Where would I include "ngSanitize". However, it crashes everything in the form when I include ngSanitize and not sure why it would

(
function(){
    var $scope, $location;
    var indexApp = angular.module('indexApp',['ui.bootstrap', 'ngSanitize']);

    indexApp.controller('IndexController',function($scope,$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.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("/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("/remote/ReturnCityList.cfm")
                    .then(function(response){
                        $scope.Cities = response.data.Cities;
                    })
            }
            catch(err){}
        }

        $scope.GetLangList = function (){
            try{
                $http.get("/remote/ReturnLangList.cfm")
                    .then(function(response){
                        $scope.Languages = response.data.Languages;
                    })
            }
            catch(err){}
        }

        $scope.SearchProvider = function(searchParam){
            try{
                $scope.searchMode = 1;
                var queryString='';
                if($scope.formModel && $scope.formModel !== searchParam){
                    $scope.resultsCount = 0;
                    currentPage = 1;
                }
                if(searchParam){
                    $scope.formModel = searchParam;
                    for(var param in searchParam){
                        if(searchParam.hasOwnProperty(param)){
                            var paramValue = searchParam[param].value ? searchParam[param].value.trim() : searchParam[param].trim();
                            if (paramValue.length > 0)
                                queryString += param + '=' + paramValue + '&';
                        }
                    }
                }
                console.log(queryString);
                queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;

                $http.get("/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); }
        }

        $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'
            };
        }
})();

推荐答案

以下是一个小提琴,演示了如何使用它,请将其应用于您的用例.

Here is a fiddle demonstrating how to use it, please apply it to your use case.

JSFiddle演示

JSFiddle Demo

<div ng-controller='MyController' ng-app="myApp">
<div id="searchResults" ng-repeat="e in Data" ng-show="ShowResults">
  <div class="row">
    <div class="col-md-4 no-margin padding">
       <strong>Data:</strong> <span ng-bind-html="e.Speciality"></span>
    </div>
 </div>
</div>

</div>

这篇关于如何在HTML实体上使用Sanitize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆