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 за планкер с кодом.

AngularJS и проверка данных формы

AngularJS Validation

Пост состоит из следующих частей:

  • Проверка данных в HTML5
  • AngularJS расширения для валидации
  • Свои кастомные проверки данных на AngularJS
  • Вывод сообщений об ошибках и ng-messages

 

Continue reading

Angular: $scope.$on() – listen to several events

I found it quite strange that AngularJS does not have possibility to watch several Angular-events, i.e.:

[javascript]
$scope.$on([‘user.login’, ‘user.logout’], callback);
[/javascript]

and I decided to extend $on method, to make it handle such case:

[javascript]
var $onOrigin = $rootScope.$on;
$rootScope.$on = function(names, listener) {
var self = this;

if (!angular.isArray(names)) {
names = [names];
}

names.forEach(function(name) {
$onOrigin.call(self, name, listener);
});

};
[/javascript]

Sandbox for this code you can find here.

 

Отличие $applyAsync от $evalAsync в Angular 1.3

Пост подготовлен на основе статьи “Scope.$applyAsync() vs. Scope.$evalAsync() in AngularJS 1.3” от Ben Nadel.

Из Angular1.2 мы все знаем метод скоупа $evalAsync, который позволяет вызывать код асинхронно (относительно цикла дайджеста) не прибегая к использованию сервиса $timeout.

В Angular1.3 был добавлен еще один метод – $applyAsync. После прочтения документации может оказаться, что по прежнему не ясно отличие этих 2х методов. С этим мы и попробуем разобраться в посте.

Continue reading

Simple script to migrate from Angular1.* to Angular2.0

Angular team is still working on this script, but Todd Motto has already provided us first version. It’s really simple:

[javascript]
var ngMigrate = (function () {

var v2uri = ‘https://code.angularjs.org/2.0.0-alpha.19/angular2.js’;

return function (version) {
var v1 = document.querySelector(‘script[src*=angular]’);
if (!v1) return;
var body = document.body;
var script = document.createElement(‘script’);
script.async = script.src = v2uri;
body.removeChild(v1);
body.appendChild(script);
};

})();

ngMigrate(‘2.0’);
[/javascript]

Here you can play with the code.

And one more brilliant idea from Todd – here – tool to define which type of service you should use (service, factory or provided). You can safely provide this link to you colleagues if somebody asks you to help with this question.

AngularJS external links

I found it was not very obvious how to have external link that coincides with you application base.

For example you have application on http://somedomain.com and on http://somedomain.com/admin you have another application. And even with href (not ng-href) and the absolute path your second application will be not accessible by link from first one. The router will keep you inside application.

The only way to solve it is to use href together with target="_self" attribute:

[javascript]
<a href="/admin" target="_self">Admin</a>
[/javascript]

And yes, this option is documented, but why it’s so hard to find?

ui-router debug snippet

found nice code snippet that could help you to debug ui-router issues by loggin router events in console:

[javascript]
// Credits: Adam`s answer in http://stackoverflow.com/a/20786262/69362
var $rootScope = angular.element(document.querySelectorAll(‘[ui-view]’)[0]).injector().get(‘$rootScope’);

$rootScope.$on(‘$stateChangeStart’,function(event, toState, toParams, fromState, fromParams){
console.log(‘$stateChangeStart to ‘+toState.to+’- fired when the transition begins. toState,toParams : \n’,toState, toParams);
});

$rootScope.$on(‘$stateChangeError’,function(event, toState, toParams, fromState, fromParams){
console.log(‘$stateChangeError – fired when an error occurs during transition.’);
console.log(arguments);
});

$rootScope.$on(‘$stateChangeSuccess’,function(event, toState, toParams, fromState, fromParams){
console.log(‘$stateChangeSuccess to ‘+toState.name+’- fired once the state transition is complete.’);
});

$rootScope.$on(‘$viewContentLoaded’,function(event){
console.log(‘$viewContentLoaded – fired after dom rendered’,event);
});

$rootScope.$on(‘$stateNotFound’,function(event, unfoundState, fromState, fromParams){
console.log(‘$stateNotFound ‘+unfoundState.to+’ – fired when a state cannot be found by its name.’);
console.log(unfoundState, fromState, fromParams);
});
[/javascript]

if you have you Angular app root on html element you can simply use:

[javascript]
var $rootScope = angular.element(document).scope();
[/javascript]

code is placed here.