【问题标题】:How can I invoke encodeURIComponent from angularJS template?如何从 angularJS 模板调用 encodeURIComponent?
【发布时间】:2013-05-13 21:16:50
【问题描述】:

我的 Angular JS 模板中有一个块

<a href="#/foos/{{foo.id}}">{{foo.name}}</a>

但是,foo.id 属性有时可能包含时髦的字符 ('/')。我想做这样的事情:

<a href="#/foos/{{encodeURIComponent(foo.id)}}">{{foo.name}}</a>

但它不起作用?我该如何解决这个问题?

【问题讨论】:

  • 我看到了这个答案 - stackoverflow.com/a/14512986/775359 - 我想知道 - 为什么我不能在模板中直接使用 encodeURIComponent... 显然需要一个过滤器。

标签: javascript html angularjs


【解决方案1】:

您可以创建一个调用encodeURIComponent的过滤器

例如

var app = angular.module('app', []);
app.filter('encodeURIComponent', function() {
    return window.encodeURIComponent;
});

那就做吧

<a href="#/foos/{{foo.id | encodeURIComponent}}">{{foo.name}}</a>

运行示例:http://jsfiddle.net/YApdK/

【讨论】:

  • jimr 打败了我,但同样值得注意的是,您应该使用 ng-href 而不是 href 以确保链接在被点击之前由 angular 呈现。
  • 只使用一个功能感觉不对,但它立即起作用。
  • 谢谢,非常令人印象深刻的例子,以非常短的语法提供 javascript 到 html
  • 正如@RickJolly 指出的那样,您应该使用ng-href 而不是href 以确保链接在被点击之前由角度呈现。您还应该将$window 注入过滤器,而不是直接使用window
【解决方案2】:

根据@aj-richardson 的建议,重新设计了@jimr 的代码。

您可以在表达式中使用过滤器在渲染数据之前对其进行格式化。

创建过滤器:

var app = angular.module('app', []);
app.filter('encodeURIComponent', function($window) {
    return $window.encodeURIComponent;
});

然后应用过滤器:

<a ng-href="#/foos/{{foo.id | encodeURIComponent}}">{{foo.name}}</a>
  • 使用ng-href 代替href 以确保链接在被点击之前由AngularJS 呈现。
  • $window 被注入过滤器,而不是直接使用window

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


参考资料:

  1. AngularJS API: $window
  2. AngularJS Developer Guide: filters
  3. AngularJS Developer Guide: expressions

【讨论】:

    【解决方案3】:

    如果要处理格式错误的 URI 错误,则必须编写一个过滤函数,然后在 encodeURIComponent 周围使用 try-catch。

    var app = angular.module('app', []);
    app.filter('encodeURIComponent', function($window) {
        return function (path) {
            try {
                return $window.encodeURIComponent(path);
            } catch(e) {
                return path;
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      相关资源
      最近更新 更多