使用AngularJS的面向对象方法

von*_*olf 8 javascript oop model-view-controller model angularjs

似乎Angular没有提供内置的解决方案来定义具有属性和方法的类实例,并且开发人员需要构建它.

在您看来,这样做的最佳做法是什么?如何将其与后端链接?

我收集的一些技巧使用工厂服务和命名功能.

资料来源: Tuto 1 Tuto 2

感谢您的见解

dom*_*kun 7

我认为最接近Object的结构可能是一个factory,原因如下:

基本语法:

.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
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

然后你可以像标准对象一样使用它:

var obj = new myFactory()

// This will of course print 'true'
console.log( obj.iAmTrue() )
Run Code Online (Sandbox Code Playgroud)

希望这有所帮助,我完全知道角度模块的第一次影响可能非常激烈......