How can I invoke encodeURIComponent from angularJS template?
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/
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.
References:
- AngularJS API: $window
- AngularJS Developer Guide: filters
- AngularJS Developer Guide: expressions