I wrote an AngularJS wrapper for p5.js called angular-p5:
angular.module('angular-p5', [])
.service('p5', ['$window', function($window) {
return $window.p5;
}])
.directive('p5', ['p5', function(p5) {
return {
restrict: 'EA',
scope: {
sketch: '='
},
link: function(scope, element, attrs) {
var sketchObj = null;
var destroySketch = function() {
if(!sketchObj) {
return;
}
sketchObj.remove();
sketchObj = null;
};
scope.$watch('sketch', function(sketch, oldSketch) {
if(oldSketch) {
destroySketch();
}
if(sketch) {
sketchObj = new p5(sketch, element[0]);
}
});
scope.$on('$destroy', destroySketch);
}
};
}]);
View the repository for angular-p5.js here on GitHub.
I have a bunch of questions... And I'm open to any and all feedback about anything I didn't mention. Hit me with your best shot!
- Naming convention - is the module name okay, or should I just name it "p5"? Or something else? Is it accepted practice for a wrapper like this to be called "angular-*", or is that considered redundant?
- Is it weird to have a service and a directive with the same name? It seemed to make sense to me, since you can inject
p5
into a controller or include<p5>
in your template. And it seems to work... but is this sort of thing common? - Does it cause any issues for
sketch
to be a function reference? (See:$scope.mySketch
.) This is a requirement of the p5 API. Again, this seems to work, but I'm not sure if this is common... - Did I handle all the cases I need to handle for observing and cleaning up the bound sketch data? Does it look like I cleaned it up properly on change and destroy?
- Is using
link
exclusively appropriate for this implementation, or should I try to factor this into a directive controller?
Also I graciously welcome any feedback about the project itself... It's fairly lightweight at the moment. Anything on GitHub is fair game if someone wants to take a look - docs, examples, etc.