[英]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. 我希望控制器中的模型不是普通对象,如
Number
, Boolean
, String
, Object
, Array
,而是由function-constructor创建的对象。
Is it possible in AngularJS? AngularJS中可能吗?
<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;
}).
// ...
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.