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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:31:35  来源:igfitidea点击:

How can I invoke encodeURIComponent from angularJS template?

javascripthtmlangularjs

提问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.

返工@jimr的代码,考虑到@ AJ-理查森的建议。

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-hrefis used instead of hrefto be sure that links are rendered by AngularJS before they can be clicked.
  • $windowis injected into the filter instead of using windowdirectly.

    You should refer to global windowthrough the $windowservice, so it may be overridden, removed or mocked for testing.

  • ng-href用于href确保链接在点击之前由 AngularJS 呈现。
  • $window注入过滤器而不是window直接使用。

    您应该window通过$window服务引用 global ,因此它可能会被覆盖、删除或模拟以进行测试。



References:

参考:

  1. AngularJS API: $window
  2. AngularJS Developer Guide: filters
  3. AngularJS Developer Guide: expressions
  1. AngularJS API:$window
  2. AngularJS 开发者指南:过滤器
  3. AngularJS 开发者指南:表达式

回答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;
        }
    }
});