How can I invoke encodeURIComponent from angularJS template?

前端 未结 3 1063
逝去的感伤
逝去的感伤 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:

    {{foo.name}}
    
    • 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

提交回复
热议问题