Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: how to extend Javascript class?

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?

like image 435
MarcoS Avatar asked Nov 01 '22 19:11

MarcoS


1 Answers

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
   };
});
like image 163
Tony Avatar answered Nov 11 '22 14:11

Tony