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

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

AngularJS: {{ }} vs ng-bind

I was just curious about this discussion on stackoverflow and decided to do own test:

[javascript]
for(var i = 0; i &lt; 100000; i++){
randomKey = randomString();
bigScope1[randomKey] = randomString();
bigScope2[randomKey] = randomString();
bigNgBindTempalte += ‘<div class="’ + randomString() + ‘" ng-bind="’+ randomKey + ‘"></div>’;
bigExpressionTemplate += ‘<div class="’ + randomString() + ‘">{{‘ + randomKey + ‘}}</div>’;
}

// console.time(‘ngBind’);
// $compile(‘<div>’ + bigNgBindTempalte + ‘</div>’)(bigScope1);
// console.timeEnd(‘ngBind’);

console.time(‘expression’);
$compile(‘<div>’ + bigExpressionTemplate + ‘</div>’)(bigScope2);
console.timeEnd(‘expression’);
[/javascript]

code.

and indeed ngBind is faster,my machine for 100000 iterations shows:

ngBind: 46984.981ms
expression: 51107.555ms

It’s still not clear why the result are so weird when you run it together (one by one). But it’s another question.

AngularJS: from 1.2 to 1.4 hints

Just a checklist to prevent issues with application migration.

Expressions

  • no .bind, .call and .apply
  • no __proto__
  • no Object

toBoolean

fixed strange behaviour (from 1.3): before ‘f’, ‘0’, ‘false’, ‘no’, ‘n’, ‘[]’  have been converted to false. Check you ng-if statements.

helpers

.copy() – makes a copy of only own properties (from 1.3)

.forEach() – does not take in account new elements (if during the loop size was changed)(from 1.3)

other

directive property replace – is now deprecated (from 1.3)

responseInterceptors property was removed from $httpProvider (from 1.3) – now it’s just $httpProvider.interceptors

$cookieStore is deprecated from 1.4 ( you should use $cookie instead)

If you know more tricky places – do not hesitate to share!

 

AngularJS: Синтаксис Controller as

Решил выложить пример кода “Controller as” в песочнице, чтобы можно было поиграться и понять, что нельзя миксовать 2 стиля написания контроллеров: либо $scope и писать просто переменные, либо this и делать синтаксис Controller as.

AngularJs: intersting syntax for complex ng-class conditions

Just now I got known quite interesting condition syntax for ng-class (from stackoverflow answer):

[javascript gutter=”0″]
ng-class="{admin:’enabled’, moderator:’disabled’, ”:’hidden’}[user.role]"
[/javascript]

it seems that there is not good explanation for such case in documentation.
being inspired by this possibility I decided to create even more complex condition:
[javascript gutter=”0″]
ng-class="connections.length && ({true:’open’, false:’close’}[!!manager.showConnections])"
[/javascript]

(flag open/close will be shown only if there are some connections for current manager)

Angular one-time binding cheat sheet

ng-bind:

[javascript gutter=”0″]
{{ ::user.name }}
[/javascript]

with filters

[javascript gutter=”0″]
{{ ::item.price|number }}
[/javascript]

ng-class:

[javascript gutter=”0″]
<div ng-class="::{ ‘active’: item.active }"></div>
[/javascript]

ng-if:

[javascript gutter=”0″]
<div ng-if="::user.isOnline"></div>
[/javascript]

with several conditions:

[javascript gutter=”0″]
<div ng-if="::(user.isOnline && users.length)"></div>
[/javascript]

ng-repeat:

[javascript gutter=”0″]
<div ng-repeat="item in ::user.items"></div>
[/javascript]

ng-options:

[javascript gutter=”0″]
<select ng-options="n.title for n in ::list"></select>
[/javascript]

directive attributes:

[javascript gutter=”0″]
<user-card user="::currentUser"></user-card>
[/javascript]
it will work even if you have two-way binging inside your directive

 

Disable chrome profile button does not work anymore

In previous chrome version it was very convenient profile switcher: it’s only 2 clicks and you are there. But they decided to update it, why? Now you have this ugly button:

not convenient profile button

instead of icon. And with this button I’ll have dropdown, then model, then…

Before it was possible to switch off this new “feature” in chrome://flags, but with new version off chrome it’s not possible anymore.

But it’s still possible to run browser with this flag (thx for @zerkms for the hint):

[shell]
–disable-new-avatar-menu
[/shell]

So I’ve created AppleScript with shell command to to run chrome with that flag:

[shell]
do shell script "/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome –disable-new-avatar-menu &
killall ChromeScript.app"
[/shell]

saved it as an application and added to startup apps list. And now I’m happy again :)

The mac chrome-runner application is on github.