Last active
December 14, 2015 16:39
-
-
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.
This file contains 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
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); | |
}); | |
} | |
}; | |
}]); |
This file contains 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
{ | |
"name": "devanand" | |
"role": "fe" | |
} |
This file contains 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
{ | |
"name": "uday" | |
"role": "fe" | |
} |
This file contains 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
<databank files="employees contractors interns"></databank> |
This file contains 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
{ | |
"name": "udai" | |
"role": "fe" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment