Html 如何从 angularJS 模板调用 encodeURIComponent?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16630471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I invoke encodeURIComponent from angularJS template?
提问by ConfusedNoob
I have a block in my angular JS template a la
我的 Angular JS 模板中有一个块
<a href="#/foos/{{foo.id}}">{{foo.name}}</a>
However, the foo.id property can sometimes contain funky characters ('/'). I want to do something like this:
但是, foo.id 属性有时可能包含时髦的字符 ('/')。我想做这样的事情:
<a href="#/foos/{{encodeURIComponent(foo.id)}}">{{foo.name}}</a>
but it doens't work? How can I fix this?
但它不起作用?我怎样才能解决这个问题?
回答by jimr
You could create a filter that calls encodeURIComponent
您可以创建一个调用的过滤器 encodeURIComponent
E.g.
例如
var app = angular.module('app', []);
app.filter('encodeURIComponent', function() {
return window.encodeURIComponent;
});
Then do
然后做
<a href="#/foos/{{foo.id | encodeURIComponent}}">{{foo.name}}</a>
Running example: http://jsfiddle.net/YApdK/
运行示例:http: //jsfiddle.net/YApdK/
回答by naXa
Reworked @jimr's code, taking into account @aj-richardson's recommendations.
You can use filters within expressions to format data before rendering it.
您可以在表达式中使用过滤器在呈现数据之前格式化数据。
Create a filter:
创建过滤器:
var app = angular.module('app', []);
app.filter('encodeURIComponent', function($window) {
return $window.encodeURIComponent;
});
Then apply the filter:
然后应用过滤器:
<a ng-href="#/foos/{{foo.id | encodeURIComponent}}">{{foo.name}}</a>
ng-href
is used instead ofhref
to be sure that links are rendered by AngularJS before they can be clicked.$window
is injected into the filter instead of usingwindow
directly.You should refer to global
window
through the$window
service, so it may be overridden, removed or mocked for testing.
ng-href
用于href
确保链接在点击之前由 AngularJS 呈现。$window
注入过滤器而不是window
直接使用。您应该
window
通过$window
服务引用 global ,因此它可能会被覆盖、删除或模拟以进行测试。
References:
参考:
回答by Fizer Khan
If you want to handle malformed URI error, then you have to write a filter function and then use try-catch around the encodeURIComponent
.
如果你想处理格式错误的 URI 错误,那么你必须编写一个过滤器函数,然后在encodeURIComponent
.
var app = angular.module('app', []);
app.filter('encodeURIComponent', function($window) {
return function (path) {
try {
return $window.encodeURIComponent(path);
} catch(e) {
return path;
}
}
});