【问题标题】:Managing models relations in AngularJS在 AngularJS 中管理模型关系
【发布时间】:2013-01-20 10:55:08
【问题描述】:

你如何管理与 AngularJS 的模型关系?在 Ember 中这很容易,但是在 AngularJS 中如何处理而不产生一堆乱七八糟的代码呢?

【问题讨论】:

  • 你能举个例子吗?在 AngularJS 中,您使用 javascript 对象进行操作,因此您可以直接引用其他对象,然后 $watch 它们(不要忘记将 true 设置为第二个参数)。还有依赖注入,所以你可以注入依赖的对象(注意value模块的方法)

标签: javascript orm angularjs


【解决方案1】:

我用https://github.com/klederson/ModelCore/,非常简单好用

var ExampleApp = angular.module('ExampleApp', ['ModelCore']); //injecting ModelCore

ExampleApp.factory("Users",function(ModelCore) {
  return ModelCore.instance({
    $type : "Users", //Define the Object type
    $pkField : "idUser", //Define the Object primary key
    $settings : {
      urls : {
        base : "http://myapi.com/users/:idUser",
      }
    },
    $myCustomMethod : function(info) { //yes you can create and apply your own custom methods
        console.log(info);
    }
  });
});

然后我只需要注入我的控制器并使用它

function MainCrtl($scope, Users) {
  //Setup a model to example a $find() call
  $scope.AllUsers = new Users();

  //Get All Users from the API
  $scope.AllUsers.$find().success(function() {
    var current;
    while(current = $scope.AllUsers.$fetch()) { //fetching on masters object
      console.log("Fetched Data into Master Object",$scope.AllUsers.$toObject()) //reading fetched from master
      //or just get the fetched object itself
      console.log("Real fetched Object",current.$toObject())
    }
  });

【讨论】:

    【解决方案2】:

    Angular 没有像 ember-data 这样的“数据存储”层,但如果您愿意,您可以集成任何现有的 ORM - What options are available for client-side JavaScript ORM?

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 2014-03-15
      相关资源
      最近更新 更多