简体   繁体   English

如何绑定由AngularJS中的函数构造函数创建的对象

[英]how to bind objects created by function-constructors in AngularJS

I want, my model in the controller, to be not a plain object like Number , Boolean , String , Object , Array , but an object created by function-constructor. 我希望控制器中的模型不是普通对象,如NumberBooleanStringObjectArray ,而是由function-constructor创建的对象。

Is it possible in AngularJS? AngularJS中可能吗?

Here is my html: 是我的html:

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

and my script: 和我的脚本:

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'};                   
}])

The constant doesn't need to be wrapped in a function... constant不需要包装在函数中...

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

// ...

http://jsfiddle.net/S5VXv/ http://jsfiddle.net/S5VXv/

The constant is immutable, to create your own-function-constructor use Factory . constant是不可变的,可以使用Factory创建自己的函数构造函数。

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

Here is docs 这是文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM