Angular + ES6 Promise

It would be really nice if we could use native ECMAScript 2015 Promises with Angular instead of $q service that is provided from box to be close to pure JavaScript:

[javascript]
//somewhere inside component controller
let promise = new Promise((resolve) => setTimeout(() => resolve(‘resolved’), 2000));
promise.then(x => this.x = x);
[/javascript]

But in this case we will have to run digest manually for each resolve(to synchronise view and model):

[javascript]
let promise = new Promise((resolve) => setTimeout(() => resolve(‘resolved’), 2000));
promise.then(x => {
$scope.apply();
this.x = x;
});
[/javascript]

But what if we hack the Promise and intercept our digest call there:

Continue reading

ui-router: Deprecated events and hooks

If you are using latest version of ui-router (now it’s 1.0.0-alpha) you probably already noticed that there are no events that we all got used to: $stateChangeCancel,  $stateChangeError, $stateChangeStart$stateChangeSuccess$stateNotFound. All of them are deprecated in 1.0.0-alpha.3 and you can not use them anymore in 1.0.0-alpha.5.

If you want to move to new version of ui-router you should make such changes:

Continue reading

ui-router: Default child for abstract state

In version 1.0.0alpha0 they finally make it possible! Child for abstract states? No! But now at least it’s possible to create own fix for it due to new $transitionsProvider, in which you could define onBefore hook. You can change the behaviour depends on state options. Let’s use “abstract” property that is boolean and extend it: to make it possible to add child state here:

[javascript]
$transitionsProvider.onBefore({
to: state => !!state.abstract
}, ($transition$, $state) => {
if (angular.isString($transition.to().abstract)) {
return $state.target($transition.to().abstract);
}
});
[/javascript]

basically if abstract param is a string we set it like a target. Example of use:

[javascript]
.state({
name: ‘abstract2’,
url: ‘/abstract2’,
abstract: ‘abstract2.foo’, // redirect to ‘abstract2.foo’
template: ‘abstract2’
})
[/javascript]

Continue reading

Understanding of component/directive attribute binding types

You probably know that directive component can have 4 different attribute-scope bindings:

  • @” – bind a local scope property to the value of DOM attribute
  • =” – set up a bidirectional binding between a local scope property and an expression passed via the attribute (also for collection “=*” and “=?” if attribute is optional)
  • <” – set up a one-way (one-directional) binding between a local scope property and an expression passed via the attribute
  • &” – provides a way to execute an expression in the context of the parent scope

So I decided to uncover magic of this symbols and recreate their functionality by using attributes from the link function.

Continue reading

ng-nl 2016. brief review

ng-nl2106 label

This year I also visited NG-NL Conference in Amsterdam and to keep the tradition will share my notes/thoughts about it.

Basically the conference was dedicated to looking deep in Angular2 parts and reactive programming experiments.

All the topics were split into 2 tracks. You can find all the program details here. My route was the following:

ng-nl-schedule

Because keynote talks were not separated and columns were not sync in time you could get the illusion of time jump.

Continue reading

AngularJS: от directive() к component()

пост был подготовлен на основе статьи Exploring the Angular 1.5 .component() method от Todd Moto.

В Angular 1.5 нам был представлен новый метод .component(), который намного проще чем .directive() и при этом он использует все лучшее по умолчанию. Метод .component() также позволит разработчикам писать в Angular2 стиле, то есть сделает переход на вторую версию максимально безболезненным.

В этом посте мы попробуем параллельно разобрать старый и новый подходы для создания компонентов.

Continue reading

AngularJS советы от команды PayPal

Перевод/формат статьи “Sane, scalable Angular apps are tricky, but not impossible. Lessons learned from PayPal Checkout.”

(Очень радует, что на зло всем критикам появляется все больше и больше серьезных приложений на AngularJS)

Continue reading

AngularJS: Зачем котроллеру ngModel нужны $formatters и $parsers

Небольшая заметка о том, для чего нужны $formatters и $parsers в контроллере ngModel директивы и когда их можно применять.

Вкратце:

  • $formatters определяют как модель будет представлена во вью
  • $parsers определяют как значения из вью будет записаны в модель

Continue reading