Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

Is it possible in AngularJS?

Here is my 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'};                   
}])
share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted

The constant doesn't need to be wrapped in a function...

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

// ...

http://jsfiddle.net/S5VXv/

share|improve this answer
    
What a stupid mistake. Thank you very much. –  Engineer Mar 20 at 7:02
add comment

The constant is immutable, to create your own-function-constructor use Factory.

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

Here is docs

share|improve this answer
    
I am new to Angular. Can you give an advice, what is the best way to create reusable classes, not singletons? –  Engineer Mar 20 at 7:05
    
All Services in Angular are singletons. But I think they are what you are definitely looking for. Here is demo to get deferences between service, factory, provider: jsfiddle.net/pkozlowski_opensource/PxdSP/14 –  Ruslan Ismagilov Mar 20 at 7:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.