How can I invoke encodeURIComponent from angularJS template?

前端 未结 3 1047
逝去的感伤
逝去的感伤 2020-12-03 07:02

I have a block in my angular JS template a la

{{foo.name}}

However, the foo.id property can s

相关标签:
3条回答
  • 2020-12-03 07:06

    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 of href to be sure that links are rendered by AngularJS before they can be clicked.
    • $window is injected into the filter instead of using window directly.

      You should refer to global window through the $window service, so it may be overridden, removed or mocked for testing.


    References:

    1. AngularJS API: $window
    2. AngularJS Developer Guide: filters
    3. AngularJS Developer Guide: expressions
    0 讨论(0)
  • 2020-12-03 07:09

    If you want to handle malformed URI error, then you have to write a filter function and then use try-catch around the encodeURIComponent.

    var app = angular.module('app', []);
    app.filter('encodeURIComponent', function($window) {
        return function (path) {
            try {
                return $window.encodeURIComponent(path);
            } catch(e) {
                return path;
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-03 07:17

    You could create a filter that calls 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/

    0 讨论(0)
提交回复
热议问题