【问题标题】:I'm confused as to where I would instantiate objects in angular我很困惑我会在哪里实例化有角度的对象
【发布时间】:2013-05-21 17:35:43
【问题描述】:

我刚刚浏览了 angularjs,它看起来很棒!但我对一些小事感到困惑。一方面,我在哪里定义我想在 elsehwere 中实例化的对象,以及如何将它们放到那里?这似乎很模糊,所以这里有一个例子

我有一个 LogObject 类,我的简单应用程序中的许多对象都派生自该类。我将它们扩展为任务、笔记、事件等。然后我有 TaskController,以及一个处理任务存储和实例化的 TaskModel。现在,我了解执行此操作的角度方法是使用 TaskController,它利用 TaskService 进行存储和其他操作。但是我在哪里/我将 Task 对象声明为?一个值?我可以让 LogObject 成为一个值,并从中扩展吗?

PA.value('LogObject',function(){
  this.title;
  this.created = new Date();
  this.text;
  this.id;
});

PA.value('Task',function(LogObject){
  angular.extend(this,LogObject)
  this.due;
  this.etc;
  this.timeLeft = function(){
 //calculate time left 
}
});

编辑

工厂对我想要的大部分工作都很有效,但我似乎无法正确扩展工厂 http://jsfiddle.net/22QLt/2/

【问题讨论】:

    标签: javascript model-view-controller inheritance angularjs


    【解决方案1】:

    您的 fiddle 存在一些问题,因此我对其进行了一些调整以使其正常工作:updated fiddle

    第一个问题是您的控制器没有连接到您的模块。

    我添加了一个body标签:

    <body ng-app='myapp'> ... </body>
    

    并将控制器声明更改为

    app.controller("HelloCtrl", function($scope, Log, DueLog){ /*...*/ });
    

    第二个问题是你使用了angular.extend。它不是 Backbone 风格的扩展,它为您提供原型继承的糖。它只是从对象复制到另一个对象。所以我编辑了你的工厂来手动实现原型继承。

    这里是所有的 JS:

    //angular.js example for factory inheritance
    var app = angular.module('myApp', []);
    
    app.factory('Log', function(){
        function Log(t) {
            this.title = t;
        }
        Log.prototype = {
            setTitle: function(t){
                this.title = t; 
                return this; // Returning the instance for chaining.
            }
        };
        return Log;
    });
    
    app.factory('DueLog', ['Log',function(Log){
        function DueLog(d) {
            Log.call(this);
            this.due = d;
        }
        DueLog.prototype = new Log();
    
        return DueLog;
    }]);
    
    app.controller('HelloCtrl', function($scope, Log, DueLog) {
        $scope.x = new Log("a").setTitle('x');
        $scope.y = new DueLog("tomorrow").setTitle('y');
    });
    

    希望这可以帮助您了解其中一些部分是如何组合在一起的。

    【讨论】:

      【解决方案2】:

      你想使用 Angular 工厂:

      http://docs.angularjs.org/guide/dev_guide.services.creating_services

      var myModule = angular.module('myModule', []);
      myModule.factory('serviceId', ['$http', function($http) {
        var items = [];
        return function(name) {
          var o = {name: name};
          items.push(o);
          return o;
        };
      }]);
      

      【讨论】:

      • 感谢您的评论。我通常会这样做,除非在所述链接的开头有一个代码示例。编辑添加代码示例
      • 等等,当一个工厂被包含在参数中时(对于DI),它包含的对象是否获得了一个实例?抱歉,你能给我举个例子吗?
      • 我试过注入+扩展。这是我的主要问题,找到一个我以后可以子类化和实例化的角度对象。实例化部分有效,但我似乎无法扩展。为什么这不起作用? jsfiddle.net/22QLt/2
      猜你喜欢
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多