我刚刚浏览了角度和开放层指令 HERE 的示例,并遇到了以下示例:
<!DOCTYPE html>
<html ng-app="demoapp">
<head>
<script src="../bower_components/openlayers3/build/ol.js"></script>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script src="../dist/angular-openlayers-directive.js"></script>
<link rel="stylesheet" href="../bower_components/openlayers3/build/ol.css" />
<script>
var app = angular.module('demoapp', ['openlayers-directive']);
app.controller('DemoController', [ '$scope', function($scope) {
angular.extend($scope, {
center: {
lat: 0,
lon: 0,
autodiscover: true
}
});
}]);
</script>
</head>
<body ng-controller="DemoController">
<openlayers ol-center="center" height="400px"></openlayers>
<h1>Center autodiscover example</h1>
<form>
Latitude : <input type="number" step="any" ng-model="center.lat" />
Longitude : <input type="number" step="any" ng-model="center.lon" />
Zoom : <input type="number" step="any" ng-model="center.zoom" />
<button ng-click="center.autodiscover=true">Discover position</button>
</form>
</body>
</html>
该示例可视为实时示例 HERE 。
我的问题是关于正在加载的文件,我不太明白为什么要加载以下脚本:
<script src="../bower_components/angular-sanitize/angular-sanitize.min.js"></script>
上述脚本的目的是什么?
编辑:: :我在角色 HERE 中找到了此模块的git repo和文档。 ,但我仍然不了解这个脚本的目的,文档甚至没有一个例子。
我已经在jQuery中编写了相当多的代码,那么有人可以用jQuery术语解释这个吗?
答案 0 :(得分:30)
如果包含angular-sanitize
脚本,则通过将HTML解析为标记来清理输入。然后将所有安全令牌(来自白名单)序列化为正确转义的html字符串。这意味着没有不安全的输入可以使它进入返回的字符串。
我在下面列出了一个受此blog post启发的小例子。如果使用var app = angular.module("app", ["ngSanitize"]);
运行此脚本,则会正确呈现html链接。但是,如果您对此语句发表评论并取消注释var app = angular.module("app", []);
,则会引发以下错误消息:Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.min.js"></script>
<!-- BEGIN disable refresh -->
<script type="text/javascript">
//Including ngSanitize ensures html links get properly sanitized
var app = angular.module("app", ["ngSanitize"]);
//If you use this code instead no html links get displayed
//var app = angular.module("app", []);
app.controller("mainController", function($scope) {
var main = this;
main.links = [
"<a href='http://google.com'>Google</a>",
"<a href='http://odetocode.com'>OdeToCode</a>",
"<a href='http://twitter.com'>Twitter</a>"
];
});
</script>
</head>
<body ng-app="app">
<section ng-controller="mainController as main">
<nav>
<ul>
<li ng-repeat="link in main.links" ng-bind-html="link">
</li>
</ul>
</nav>
</section>
</body>
</html>