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

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

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

 

AngularJS: How to pass a method into an isolated scope

I came to conclusion that it’s not very obvious how to pass a method into an isolated scope. And that’s why my junior AngularJS developers just do direct call:

[javascript]
$scope.$parent.methodOfParentScope();
[/javascript]

but it’s more like a hack. It’s more correct to pass it via attribute:

Continue reading

Load remote script from your userscript extension

Just not to lose snippet/solution that I’d been looking for quite some time paste it here:

[javascript]
var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};
[/javascript]

and example (loading jQuery):

[javascript]
loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
$("#answer-6825715").css("border", ".5em solid black");
});
[/javascript]

taken from stackoverflow.

How to catch Angular ui-router resolve errors

It’s more than annoying to have just a blank page and no errors in console when your issue is inside ui-router resolve. Finally I found a pretty nice solution, don’t know why it’s not provided “from the box”. In case of error ui-router sends specific event $stateChangeError that we could listen for:

[javascript]
$rootScope.$on(‘$stateChangeError’, function(event, toState, toParams, fromState, fromParams, error){
console.error(error);
});
[/javascript]

and now wow! we have an exact error in console and no need to guess what’s wrong with your code anymore.

AngularJS: ng-click и ng-disabled

Учтите что ng-disable работает только на элементах формы, поэтому тут

[html]

<div ng-click="doAction()" ng-disabled="buttonDisable">Click Me</div>

[/html]

директива ng-click отрабатывает клик.

Если необходимо использовать ng-disable могу предложить такой вот хак:

[html]
<div ng-click="buttonDisable || doAction()" ng-disabled="buttonDisable</div>
[/html]

 

P.S.: Большоя спасибо Vitalii Hudyma за планкер с кодом.