Skip to content

Instantly share code, notes, and snippets.

@udayms
Last active December 14, 2015 16:39
Show Gist options
  • Save udayms/5116839 to your computer and use it in GitHub Desktop.
Save udayms/5116839 to your computer and use it in GitHub Desktop.
An AngularJS directive that loads json files from the list of files supplied in the html element and stores the data in $rootScope.db. It also fires an event databank-ready that can be listened to from the controller. Thanks to Clint Checketts for helping me debug this.
app.directive('databank', ['$parse','$http', '$rootScope', function($parse, $http, $rootScope) {
return {
restrict: 'E',
replace: true,
scope: { accept: "=",fn:"=onReady" },
link: function(scope, elem, attr){
var files = attr.files.split(' ');
var promises = {};
var db = {};
angular.forEach(files, function(file) {
promises[file] = $http.get(file + '.json');
});
var i = 1;
angular.forEach(promises, function(req, name){
req.then(function(res){
db[name] = res.data;
if(files.length == i){
$rootScope.db = db;
$rootScope.$broadcast('databank-ready', db);
}
i++;
});
});
scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(scope.fn && (typeof(scope.fn) === 'function')) {
fn();
}
} else {
this.$apply(scope.fn);
}
};
scope.safeApply(function() {
scope.fn(scope);
});
}
};
}]);
{
"name": "devanand"
"role": "fe"
}
{
"name": "uday"
"role": "fe"
}
<databank files="employees contractors interns"></databank>
{
"name": "udai"
"role": "fe"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment