Encapsulation of Nick Galbreath's base64.js library for AngularJS
For Base64 encoding whch supports UTF8 see angular-utf8-base64
bower install angular-base64
NB: The ngBase64
bower package is deprecated due to camel casing issues on case-sensitive file systems.
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);
You can encode unicode strings using base64 as described here.
angular
.module('myApp', ['base64'])
.controller('myUnicodeController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode(unescape(encodeURIComponent('โ a string')));
$scope.decoded = decodeURIComponent(escape($base64.decode('4pyTIGEgc3RyaW5n')));
}]);
If you want to transmit a base64 encoded string in a url you must make it "URL safe" by encoding it with encodeURIComponent
.
var base64EncodedString = $base64.encode('a string');
var urlSafeBase64EncodedString = encodeURIComponent(base64EncodedString);
To decode the above string use decodeURIComponent
, then decode
.
var base64EncodedString = decodeURIComponent('YSBzdHJpbmc%3D');
var decodedString = $base64.decode(base64EncodedString);