Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object oriented approach with AngularJS

It seems that Angular does not provide a built-in solution to define class instances with properties and methods and that it's up the developer to build this.

What is the best practice to do this in your opinion? How to you link this with the backend?

Some of the tips I have gathered use factory services and named functions.

Sources : Tuto 1 Tuto 2

Thanks for your insights

like image 433
vonwolf Avatar asked Jul 03 '14 07:07

vonwolf


1 Answers

I think that the closest structure to an Object it's probably a factory, for several reasons:

Basic Syntax:

.factory('myFactory', function (anInjectable) {

  // This can be seen as a private function, since cannot
  // be accessed from outside of the factory 
  var privateFunction = function (data) {
    // do something 
    return data
  }

  // Here you can have some logic that will be run when 
  // you instantiate the factory
  var somethingUseful = anInjectable.get()
  var newThing = privateFunction(somethingUseful)

  // Here starts your public APIs (public methods)
  return {
    iAmTrue: function () {
      return true
    },

    iAmFalse: function () {
      return false
    },

    iAmConfused: function () {
      return null
    }
  }
})

And then you can use it like a standard Object:

var obj = new myFactory()

// This will of course print 'true'
console.log( obj.iAmTrue() )

Hope this helps, I perfectly know that the first impact with angular modules can be pretty intense...

like image 188
domokun Avatar answered Oct 07 '22 15:10

domokun