Created
August 1, 2013 16:57
-
-
Save ramon/6133208 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
//= require chosen.jquery.js | |
!(function (angular) { | |
"use strict"; | |
angular.module('ui.chosen', []) | |
.value('chosenConstants', { | |
'REGEXP': /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, | |
'WHITELIST': ['noResultsText', 'allowSingleDeselect', 'disableSearchThreshold', 'disableSearch'] | |
}) | |
.directive('chosen', ['$timeout', 'chosenConstants', function($timeout, chosenConstants) { | |
function snakeCase(input) { | |
return input.replace(/[A-Z]/g, function($1) { return "_" + $1.toLowerCase(); }); | |
} | |
function isEmpty(value) { | |
if (angular.isArray(value)) { | |
return value.length === 0; | |
} | |
else if (angular.isObject(value)) { | |
for(var key in value) { | |
if (value.hasOwnProperty(key)) { return false; } | |
} | |
} | |
return true; | |
} | |
return { | |
restrict: 'A', | |
link: function (scope, element, attr) { | |
var options = scope.$eval(attr.chosen) || {}; | |
angular.forEach(attr, function(value, key) { | |
if (angular.isDefined(chosenConstants.WHITELIST[key])) { | |
options[snakeCase(key)] = scope.$eval(value); | |
} | |
}); | |
var startLoading = function() { | |
element.addClass('loading').attr('disabled', true).trigger('chosen:updated'); | |
}; | |
var stopLoading = function() { | |
element.removeClass('loading').attr('disabled', false).trigger('chosen:updated'); | |
}; | |
var disableWithMessage = function(message) { | |
element.empty().append("<option selected>" + message + "</option>").attr('disabled', true).trigger('chosen:updated'); | |
}; | |
$timeout(function() { | |
element.chosen(options); | |
}); | |
if (angular.isDefined(attr.ngOptions)) { | |
var match = attr.ngOptions.match(chosenConstants.REGEXP), | |
valueExpr = match.pop(); | |
console.log('chosen', match, valueExpr, scope.$eval(valueExpr)); | |
if(angular.isUndefined(scope.$eval(valueExpr))) { startLoading(); } | |
scope.$watch(valueExpr, function(newVal, oldVal) { | |
if (newVal !== oldVal) { | |
$timeout(stopLoading); | |
debugger; | |
if (isEmpty(newVal)) { | |
disableWithMessage(options.no_result_text || 'Sem valores disponiveis'); | |
} | |
} | |
}, true); | |
} | |
} | |
}; | |
}]) | |
; | |
}(angular)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment