Created
August 20, 2015 14:49
-
-
Save mlent/571377d1f37ec7a12179 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var modules = require('modules'); | |
var DIRECTIVE_NAME = 'validationList'; | |
function validationList() { | |
return { | |
restrict: 'C', | |
link: function(scope, elem, attrs) { | |
var liExprs = []; | |
var lis = elem.children(); | |
var ngAttrs = ['ng-show', 'ng-if', 'ng-hide']; | |
var ulExpr = extractExprs(elem[0], ngAttrs); | |
// First, snag the expressions being used to show the UL's children | |
_.forEach(lis, function(li) { | |
liExprs.push(extractExprs(li, ngAttrs)); | |
}); | |
// All conditions must be met | |
var watchExpr = ulExpr.join(' && ') + ((ulExpr.length && liExprs.length) ? ' && ' : ''); | |
// The expression used to show the UL, must be combined | |
// with that of the children. | |
watchExpr += liExprs.length ? '(' + liExprs.join(' || ') + ')' : ''; | |
// Set this up as the watch expr. | |
var evaluator = function() { | |
return scope.$eval(watchExpr); | |
}; | |
// If the watch expression evaluates to true, | |
// it means that the list + an error is displaying. | |
// So, add the class | |
scope.$watch(evaluator, function(newVal, oldVal) { | |
if (newVal === oldVal) { return; } | |
elem.parent().toggleClass('active-validation-list', newVal); | |
}); | |
/** | |
* @param {object} el - The element to extract expressions from | |
* (Not an angular.element, but a DOM node) | |
* @param {array} attrs - Array of attributes to extract. | |
*/ | |
function extractExprs(el, attrs) { | |
var found = _.map(attrs, function(a) { | |
var expr = el.getAttribute(a); | |
if (!expr) { return null; } | |
// If it's an ng-hide, inverse the logic so it matches | |
return a === 'ng-hide' ? '!(' + expr + ')' : expr; | |
}); | |
return _.compact(found); | |
} | |
} | |
}; | |
} | |
modules.common.directive(DIRECTIVE_NAME, validationList); | |
module.exports = { | |
name: DIRECTIVE_NAME, | |
component: validationList | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment