AngularJS 的面向对象方法 [英] Object oriented approach with AngularJS

查看:21
本文介绍了AngularJS 的面向对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

来源:教程 1教程 2

感谢您的见解

推荐答案

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

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

基本语法:

.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() )

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

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

这篇关于AngularJS 的面向对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆