There’s more than one way to perform i18n translations within our AngularJS projects. IMHO the best one is https://angular-translate.github.io/, but today I’m going to show you how I’m doing translations in my small AngularJS projects (normally Ionic projects).
I’ve packaged my custom solution and I also create one bower package ready to use via bower command line:
And now we add our new module (‘gonzalo123.i18n’) to our AngularJS project
[sourcecode language=”js”]
angular.module(‘G’, [‘ionic’, ‘ngCordova’, ‘gonzalo123.i18n’])
[/sourcecode]
Now we’re ready to initialise our provider with the default language and translation data
I like to use constants to store default lang and translation table, but it isn’t necessary. We can just pass the default language and Lang object to our provider
And that’s all. We can translate key in templates (the project also provides a filter):
[sourcecode language=”html”]
<h1 class="title">{{ ‘HI’ | i18n }}</h1>
[/sourcecode]
And also inside our controllers
[sourcecode language=”js”]
.controller(‘HomeController’, function ($scope, i18n) {
$scope.hi = i18n.traslate(‘HI’);
})
[/sourcecode]
If we need to change user language, we only need to trigger ‘use’ function:
[sourcecode language=”js”]
.controller(‘HomeController’, function ($scope, i18n) {
$scope.changeLang = function(lang) {
i18n.use(lang);
};
})
[/sourcecode]
Here we can see the code of our provider:
[sourcecode language=”js”]
(function () {
"use strict";
angular.module(‘gonzalo123.i8n’, [])
.provider(‘i18n’, function () {
var myLang = {},
userLang = ‘en’,
translate;
translate = function (key) {
if (myLang.hasOwnProperty(key)) {
return myLang[key][userLang] || key;
} else {
return key;
}
};
Another crazy idea. I want to dump my backend output in the browser’s console. There’re several PHP dumpers. For example Raul Fraile’s LadyBug. There’re also libraries to do exactly what I want to do, such as Chrome Logger. But I wanted to use Websockets and dump values in real time, without waiting to the end of backend script. Why? The answer is simple: Because I wanted to it 🙂
I’ve written several post about Websockets, Silex, PHP. In this case I’ll use a similar approach than the previous posts. First I’ve created a simple Webscocket server with socket.io. This server also starts a Express server to handle internal messages from the Silex Backend
io.sockets.on(‘connection’, function (socket) {
console.log("Socket connected!");
});
expressApp.listen(CONF.EXPRESS.PORT, CONF.EXPRESS.HOST, function () {
console.log(‘Express started’);
});
server.listen(CONF.IO.PORT, CONF.IO.HOST, function () {
console.log(‘IO started’);
});
[/sourcecode]
Now we create a simple Service provider to connect our Silex Backend to our Express server (and send the dumper’s messages using the websocket connection)
[sourcecode language=”php”]
<?php
namespace Dumper\Silex\Provider;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Dumper\Dumper;
use Silex\Provider\SessionServiceProvider;
use GuzzleHttp\Client;
class DumperServiceProvider implements ServiceProviderInterface
{
private $wsConnector;
private $client;
public function __construct(Client $client, $wsConnector)
{
$this->client = $client;
$this->wsConnector = $wsConnector;
}
public function register(Application $app)
{
$app->register(new SessionServiceProvider());
$app[‘dumper’] = function () use ($app) {
return new Dumper($this->client, $this->wsConnector, $app[‘session’]->get(‘uid’));
};
$app[‘dumper.init’] = $app->protect(function ($uid) use ($app) {
$app[‘session’]->set(‘uid’, $uid);
});
$app[‘dumper.uid’] = function () use ($app) {
return $app[‘session’]->get(‘uid’);
};
}
public function boot(Application $app)
{
}
}
[/sourcecode]
Finally our Silex Application looks like that:
[sourcecode language=”php”]
include __DIR__ . ‘/../vendor/autoload.php’;
use Silex\Application;
use Silex\Provider\TwigServiceProvider;
use Dumper\Silex\Provider\DumperServiceProvider;
use GuzzleHttp\Client;
$app->get(‘/api/hello’, function (Application $app) {
$app[‘dumper’]->error("Hello world1");
$app[‘dumper’]->info([1,2,3]);
return $app->json(‘OK’);
});
$app->run();
[/sourcecode]
In the client side we have one index.html. I’ve created Twig template to pass uid to the dumper object (the websocket channel to listen to), but we also can fetch this uid from the backend with one ajax call.
<!– We use jQuery just for the demo. Library doesn’t need jQuery –>
<script src="assets/jquery/dist/jquery.min.js"></script>
<!– We load the library –>
<script src="js/dumper.js"></script>
<script>
dumper.startSocketIo(‘{{ uid }}’, ‘//localhost:8888’);
function api(name) {
// we perform a remote api ajax call that triggers websockets
$.getJSON(‘/api/’ + name, function (data) {
// Doing nothing. We only call the api to test php dumper
});
}
</script>
</body>
</html>
[/sourcecode]
I use jQuery to handle ajax request and to connect to the websocket dumper object (it doesn’t deppend on jQuery, only depend on socket.io)
[sourcecode language=”js”]
var dumper = (function () {
var socket, sessionUid, socketUri, init;
init = function () {
if (typeof(io) === ‘undefined’) {
setTimeout(init, 100);
} else {
socket = io(socketUri);
socket.on(‘dumper.’ + sessionUid, function (data) {
console.group(‘Dumper:’, data.title);
switch (data.title) {
case ’emergency’:
case ‘alert’:
case ‘critical’:
case ‘error’:
console.error(data.data);
break;
case ‘warning’:
console.warn(data.data);
break;
case ‘notice’:
case ‘info’:
//case ‘debug’:
console.info(data.data);
break;
default:
console.log(data.data);
}
console.groupEnd();
});
}
};
return {
startSocketIo: function (uid, uri) {
var script = document.createElement(‘script’);
var node = document.getElementsByTagName(‘script’)[0];
One typical task when we work with AngularJs application is login, and private states. We can create different states in our application. Something like this:
And then we can check out this parameters within $stateChangeStart event, doing one thing or another depending on token is present or not
[sourcecode language=”js”]
.run(function ($rootScope) {
$rootScope.$on("$stateChangeStart", function (event, toState) {
if (toState.data && toState.data.isPublic) {
// do something here with localstorage and auth token
}
});
})
[/sourcecode]
This method works, but last days, reading one project of Aaron K Saunders at github, I just realised that there’s another method. We can listen to $stateChangeError. Let me show you how can we do it.
The idea is to use resolve in our private states. With resolve we can inject objects to our state’s controllers, for example user information. This method is triggered before call to the controller, so that’s a good place to check if token is present. If it isn’t, then we can raise an error. This error will trigger $stateChangeError event, and here we can redirect the user to login state.
It sounds good, but we need to write resolve parameter in every private states, and that’s bored. Especially when all states are private except login state. To by-pass this problem we can use abstract states. The idea is simple, we define one abstract state with “resolve” and then we create our private states under this abstract state.
Here we can see one example: login state isn’t private, but state1 and state2 are private, indeed.
Our UserService is a AngularJS service. This service provides three methods: init (the method that raises an error if token isn’t present), login (to perform login and validate credentials), and logout (to remove token from localstorage and redirects to login state)
[sourcecode language=”js”]
.service(‘UserService’, function ($q, $state) {
var user = undefined;
var UserService = {
init: function () {
var deferred = $q.defer();
// do something here to get user from localstorage
And that’s all. IMHO this solution is cleaner than $stateChangeStart method. What do you think?
WARNING!
Before publishing this post I realize that this technique doesn’t work 100% correctly. Maybe is my implementation but I tried to use it with an ionic application and it doesn’t work with android. Something kinda weird. It works with web applications, it works with IOS, but it doesn’t work with Android. It looks like a bug (not sure about it). Blank screen instead of showing the template (but controller is loaded). We can see this anomalous situation using “ionic serve -l” (IOS ok and Android Not Ok)
To bypass this problem I tried a workaround. instead of using abstract states I create normal states, but to avoid to write again and again the resolve function to mark private states, I create a privateState provider
[sourcecode language=”js”]
.provider(‘privateState’, function () {
this.$get = function () {
return {};
};
This days I’ve been playing with hello.js. Hello is a A client-side Javascript SDK for authenticating with OAuth2 web services. It’s pretty straightforward to use and well explained at documentation. I want to use it within AngularJS projects. OK, I can include the library and use the global variable “hello”, but it isn’t cool. I want to create a reusable module and available with Bower. Let’s start.
Our ng-hello is just a service provider that wraps hello.js
[sourcecode language=”js”]
(function (hello) {
angular.module(‘ngHello’, [])
.provider(‘hello’, function () {
this.$get = function () {
return hello;
};
Last days I’ve been playing with OpenUI5. OpenUI5 is a web toolkit that SAP people has released as an open source project. I’ve read several good reviews about this framework, and because of that I started to hack a little bit with it. OpenUI5 came with a very complete set of controls. In this small example I want to use the “table” control. It’s just a datagrid. This days I playing a lot with Angular.js so I wanted to use together OpenUI5’s table control and Angularjs.
I’m not quite sure if it’s a good decision to use together both frameworks. In fact we don’t need Angular.js to create web applications using OpenUI5. OpenUI5 uses internally jQuery, but I wanted to hack a little bit and create one Angularjs directive to enclose one OpenUI5 datagrid.
First of all, we create one index.html. It’s just a boilerplate with angular + ui-router + ui-bootstrap. We also start our OpenUi5 environment with de default theme and including the table library
And now we can create a simple Angular.js using the ng.openui5 module. In this application we configure the table and fetch the data from an externar API server
Today an original post. Maybe I’m the only one doing this, I know. 2014 is close to finish and I want to review how it went the year. Let’s start.
The bad parts:
My book about SOLID principles (in Spanish) isn’t released yet. It’s almost finished. It only needs a few reviews, but because one thing or another it looks like it isn’t be released this year. Lesson learned: Those kind of side projects must have a release date. If they haven’t, another side projects can grab our attention and they can be frozen.
No new languages learned this year. There was a good chance with Swift. A new language, but it didn’t attract my attention. Erlang books are still in my desk and also my aim to improve my Java skills didn’t success. I found nothing where apply my Java learning.
The good parts:
Finally I can say JavaScript is a first class language within my personal software stack. Various projects with JS this year and I feel very comfortable writing JavaScript code. That’s also the year of Angular.js (for me and probably a lot of people).
This year has been the year of mobile development for me. I’ve been involved with several projects using Cordova/Phonegap framework. I the beginning to install Cordova environment, compile, deploy the application into the device was something “heroic” but now it turns into trivial operations. I still remember my beginning with jQuery Mobile. Horrible. Then I started using Angular.js and Topcoat. Much better, but still problems when switching between Android and IOs. Finally I re-discover Ionic framework. Incredible project. Hybrid applications with angular.js with very complete toolkit. This year has been crowed by push notifications, camera plugins, barcode scanners, token based authorisations, Websockets and things like that. Now hybrid applications with Phonegap/Cordova live in my comfort zone along with Silex, Angular, PHP… (that’s means I need to find other places outside it)
The last part of the year I’ve been working a lot with automation tools: Bower and Grunt mainly. I also started to work with JavaScript testing with Karma and Jasmine
This year I’ve been a proud speaker at DeSymfony Day in Barcelona. On incredible weekend. Meeting with colleagues, speaker dinner, great conversations, and tourism in a great city. Definitely the most beautiful room for a conference that I ever been
Katayunos The coding dojo where we play with TDD and Pair Programming is still alive. Maybe not as continuous as I’d like, but we still meet together 20-25 people one Saturday morning to improve our programming skill, from time to time
My personal blog is still alive too. It’s close to be 5 years old (OK, technically speaking 6, but first year it wasn’t a serious one). More than 20k views per month and sometimes close to 30k (Hey, thank you for reading!)
And that’s all. It was a good year. Hopefully it will be worse than 2015 🙂
I really like WebSockets. I’ve written several posts about them. Today we’re going to speak about something related to WebSockets. Let me explain it a little bit.
Imagine that we build a Web Application with WebSockets. That’s means that when we start the application, we need to connect to the WebSockets server. If our application is a Single-page application, we’ll create one socket per application, but: What happens if we open three tabs with the application within the browser? The answer is simple, we’ll create three sockets. Also, if we reload one tab (a full refresh) we’ll disconnect our socket and reconnect again. Maybe we can handle this situation, but we can easily bypass this disconnect-connect situation with a HTML5 feature called SharedWorkers.
Web Workers allows us to run JavaScript process in background. We also can create Shared Workers. SharedWorkers can be shared within our browser session. That’s means that we can enclose our WebSocket server inside s SharedWorker, and if we open various tabs with our browser we only need one Socket (one socket per session instead one socket per tab).
I’ve written a simple library called gio to perform this operation. gio uses socket.io to create WebSockets. WebWorker is a new HTML5 feature and it needs a modern browser. Socket.io works also with old browsers. It checks if WebWorkers are available and if they isn’t, then gio creates a WebSocket connection instead of using a WebWorker to enclose the WebSockets.
We can see one simple video to see how it works. In the video we can see how sockets are created. Only one socket is created even if we open more than one tab in our browser. But if we open a new session (one incognito session for example), a new socket is created
Here we can see the SharedWorker code:
[sourcecode language=”js”]
"use strict";
importScripts(‘socket.io.js’);
var socket = io(self.name),
ports = [];
addEventListener(‘connect’, function (event) {
var port = event.ports[0];
ports.push(port);
port.start();
port.addEventListener("message", function (event) {
for (var i = 0; i < event.data.events.length; ++i) {
var eventName = event.data.events[i];
socket.on(‘connect’, function () {
for (var i = 0; i < ports.length; i++) {
ports[i].postMessage({type: ‘_connect’});
}
});
socket.on(‘disconnect’, function () {
for (var i = 0; i < ports.length; i++) {
ports[i].postMessage({type: ‘_disconnect’});
}
});
[/sourcecode]
And here we can see the gio source code:
[sourcecode language=”js”]
var gio = function (uri, onConnect, onDisConnect) {
"use strict";
var worker, onError, workerUri, events = {};
function getKeys(obj) {
var keys = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push(i);
}
}
return keys;
}
function onMessage(type, message) {
switch (type) {
case ‘_connect’:
if (onConnect) onConnect();
break;
case ‘_disconnect’:
if (onDisConnect) onDisConnect();
break;
default:
if (events[type]) events[type](message);
}
}
function startWorker() {
worker = new SharedWorker(workerUri, uri);
worker.port.addEventListener("message", function (event) {
onMessage(event.data.type, event.data.message);
}, false);
worker.onerror = function (evt) {
if (onError) onError(evt);
};
I’ve also created a simple webSocket server with socket.io. In this small server there’s a setInterval function broadcasting one message to all clients per second to see the application working
[sourcecode language=”js”]
var io, connectedSockets;
Remember my last post about WebSockets and AngularJs? Today we’re going to play with something similar. I want to create a key-value interface to play with websockets. Let me explain it a little bit.
First we’re going to see the backend. One Silex application with two routes: a get one and a post one:
[sourcecode language=”php”]
<?php
include __DIR__ . ‘/../../vendor/autoload.php’;
include __DIR__ . ‘/SqlLiteStorage.php’;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Silex\Provider\DoctrineServiceProvider;
interface StorageIface
{
public function get($key);
public function post($key, $value);
}
[/sourcecode]
Our implementation uses SqlLite, but it’s pretty straightforward to change to another Database Storage or even a NoSql Database.
[sourcecode language=”php”]
use Doctrine\DBAL\Connection;
use G\Io\Storage\StorageIface;
class SqlLiteStorage implements StorageIface
{
private $db;
public function __construct(Connection $db)
{
$this->db = $db;
}
public function get($key)
{
$statement = $this->db->executeQuery(‘select value from storage where key = :KEY’, [‘KEY’ => $key]);
$data = $statement->fetchAll();
Angular creates one $scope object for each controller. We also have a $rootScope accesible from every controllers. But, can we access to one controller’s $scope from another controller? The sort answer is no. Also if our application needs to access to another controller’s $scope, we probably are doing something wrong and we need to re-think our problem. But anyway it’s possible to access to another controller’s $scope if we store it within a service. Let me show you and example.
And now we need to store the $scope in the service:
[sourcecode language=”js”]
app.controller(‘OneController’, function ($scope, Scopes) {
Scopes.store(‘OneController’, $scope);
…
});
app.controller(‘TwoController’, function ($scope, Scopes) {
Scopes.store(‘TwoController’, $scope);
…
});
[/sourcecode]
$scope.buttonClickOnOneController = function () {
Scopes.get(‘OneController’).buttonClick();
};
});
app.factory(‘Scopes’, function ($rootScope) {
var mem = {};
I’m a big fan of websockets. I’ve got various post about them (here, here). Last months I’m working with angularjs projects and because of that I wanna play a little bit with websockets (with socket.io) and angularjs.
I want to build one angular service.
[sourcecode language=”js”]
angular.module(‘io.service’, []).
factory(‘io’, function ($http) {
var socket,
apiServer,
ioEvent,
watches = {};
The idea of the application is to watch one model’s variable (‘question’ in this example) and each time it changes we will send the value to the websocket server and we’ll so something (we will convert the string to upper case in our example)
As you can read in one of my previous post I don’t like to send messages from the web browser to the websocket server directly (due do to authentication issues commented here). I prefer to use one server (a Silex server in this example)
[sourcecode language=”php”]
include __DIR__ . ‘/../../vendor/autoload.php’;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
$app = new Application([‘debug’ => true]);
$app->register(new G\Io\EmitterServiceProvider());
$app->get(‘/request’, function (Application $app, Request $request) {