Skip to content

Instantly share code, notes, and snippets.

@paveleremin
Created May 12, 2015 18:42
Show Gist options
  • Save paveleremin/cdec2855d8125bad4c18 to your computer and use it in GitHub Desktop.
Save paveleremin/cdec2855d8125bad4c18 to your computer and use it in GitHub Desktop.
[Examples] Directive
'use strict';
angular.module('SomeProject')
.directive('selectVehicleColor', function(){
return {
scope: {
model: '=',
colors: '=selectVehicleColor',
title: '@'
},
replace: true,
restrict: 'A',
templateUrl: 'selectVehicleColorTemplate',
link: function (scope, element){
var elementIsBinded = false,
leaveTimeout,
waitForData;
// requires a unique identifier to use several times
scope.instanceId = Math.random().toString(36).substring(7);
// waiting for colors array
waitForData = scope.$watch('colors', function(newValue){
if (!newValue || !newValue.length) return;
waitForData();
// bind element
element.on('click', function(e){
if (scope.isExpanded) {
e.stopPropagation();
return;
}
scope.isExpanded = true;
scope.$apply();
// element already binded
if (elementIsBinded) return;
elementIsBinded = true;
element.on('mouseleave', function(){
leaveTimeout = setTimeout(function(){
if (!scope.isExpanded) return;
scope.isExpanded = false;
scope.$apply();
}, 500);
});
element.on('mouseenter', function(){
!leaveTimeout || clearTimeout(leaveTimeout);
});
});
// bind labels
element.find('label').on('click', function(e){
if (!scope.isExpanded) {
e.stopPropagation();
return;
}
var value = angular.element(this).prev().val();
if (value === '') {
delete scope.model;
}
else {
scope.model = value;
}
scope.$apply();
setTimeout(function(){
scope.isExpanded = false;
scope.$apply();
}, 50);
});
// add class to set block height
element.addClass('items-'+scope.colors.length);
// watch for direct changes
scope.$watch('model', function (newValue, oldValue){
var state = !angular.isDefined(oldValue),
elementSelector = angular.isDefined(oldValue)
? '#'+scope.instanceId+oldValue
: '#'+scope.instanceId+newValue;
angular.element(elementSelector).prop('checked', state);
});
});
//garbage collector
scope.$on('$destroy', function(){
element.off('click mouseleave mouseenter');
element.find('label').off('click');
});
}
};
})
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment