0

I'm trying to create a model with AngularJS the way Backbone has the capability of doing it:

User = Backbone.Model.extend({

defaults: function() {
  return {
      "name": "finding name...",
      "id" : "",
      "age" : "",
      "gender" : ""
    };
 };

So I can later do something like var user = new User();

I found this backbone-style models in angularjs? and I'm just trying to verify that there's no way of doing the above but through a factory?

1
  • If you need to make changes to the way your data in handled look at all the providers like "factorys" and "services", but, You also have to remember that a model like this will normally exist within the html and the $scope to which is binding. I would just push into your $scope array and $watch it to maintain persistence. If you have a special way that you want to handle the your data outside of Angular, just use regular objects, because in this instance, the Backbone is just a wrapper for prototype. Commented Aug 27, 2013 at 18:57

2 Answers 2

1

You can use the value method of a module to store a function instead of having a factory returning a function like this :

var myApp = angular.module('myApp', []);

myApp.value('User', function () {
        return {
            "name": "finding name...",
            "id": "",
            "age": "",
            "gender": ""
        };
});

function ctrl($scope, User) {
    var user = new User();
    console.log(user);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use factory to return a function and then you will be able to use the keyword new to create a new object.

var myApp = angular.module('myApp', []);
myApp.factory('User', function () {
    return function () {
        return {
            "name": "finding name...",
            "id": "",
            "age": "",
            "gender": ""
        };
    };
});

function ctrl($scope, User) {
    var user = new User();
    console.log(user);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.