I'm writing my first new Angularjs project.
I need to add my custom method (say, addHours()
), to a javascript class, say Date()
.
For completeness, this is my (working) method:
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + parseInt(h));
return this;
}
Which is the recommended way to do it? Where to put the prototype functions, so they are available through all my project? Should I better create a new Date class? Should I better define an angular service?
Maybe this article can give you some insight.
Additionally, you could just include that snippet in a JS file on your index.html which would make all Date objects in your application have addHours
. I tend to do this for any standard library 'enhancements' so I can easily identify where the standard library objects deviate.
Update:
A concrete example following along with the article, for the most part:
yourApp.factory( 'MyDate', function() {
//Constructor
function MyDate( date ) {
this.date = date; //Wrapping a JS date object.
//Probably want to add some safety here to make sure it IS a date obj
}
MyDate.prototype.addHours( h ) {
this.date.setHours( this.date.getHours() + parseInt(h) );
}
return MyDate;
});
yourApp.controller( 'MyDateController', function( $scope, MyDate ) {
$scope.someMethod = function(h) {
//Some trigger, UI or what not
$scope.myDate = new MyDate( new Date() );
$scope.myDate.addHours(h);
//Do something with the new date
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With