【问题标题】:how to bind objects created by function-constructors in AngularJS如何在 AngularJS 中绑定由函数构造函数创建的对象
【发布时间】:2023-03-03 09:48:01
【问题描述】:

我希望,我在控制器中的模型,不是像NumberBooleanStringObjectArray 这样的普通对象,而是由函数构造函数创建的对象。

在 AngularJS 中可以吗?

Here是我的html:

<body ng-app="MyApp" ng-controller="MyController">
   <input ng-model="model.text" type="text"/>
</body>

还有我的脚本:

angular.module('MyApp',[]).
constant('MyModel',function(){
    var MyModel = function(text){
        this.text = text;
    };

    return MyModel;
}).
controller('MyController',
           [
               '$scope',
               'MyModel',
               function(
                   $scope,
                   MyModel
               ){
    //Does not work               
    $scope.model = new MyModel('dummy text');
    //Works
    //$scope.model = {text:'dummy text'};                   
}])

【问题讨论】:

    标签: javascript angularjs data-binding model angularjs-scope


    【解决方案1】:

    constant 不需要包装在函数中...

    angular.module('MyApp',[]).
    constant('MyModel',function(text){
            this.text = text;
    }).
    
    // ...
    

    http://jsfiddle.net/S5VXv/

    【讨论】:

      【解决方案2】:

      constant 是不可变的,要创建自己的函数构造函数,请使用 Factory

      angular.module('MyApp',[])
        .factory('MyModel',function(){
          var MyModel = function(text){
            this.text = text;
          };
          return MyModel;
      });
      

      Here is docs

      【讨论】:

      • 我是 Angular 的新手。您能给个建议吗,创建可重用类而不是单例的最佳方法是什么?
      • Angular 中的所有服务都是单例的。但我认为它们是您肯定要寻找的。这里是获得服务,工厂,提供者之间的尊重的演示:jsfiddle.net/pkozlowski_opensource/PxdSP/14
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多