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:
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;
}
}
});
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/