1

I have an object representing a person:

function Person(_name) {
    this.name = _name;

    this.start = function() {
        var that = this
        $timeout( function sayHello() {
            console.log(that.name);
            $timeout(sayHello, 1000);
        }, 1000);
    }
}

Notice that is uses the angular $timeout service. Where should I put this so that I can declare people in my controller:

function Ctrl($scope) {

    // How do I access Person so I can do this?
    $scope.p1 = Person('nick');
    $scope.p2 = Person('amy');
    $scope.p1.start();
    $scope.p2.start();
}

I can put the declaration in the controller body, and it works but that doesn't seen like good design. I'm pretty sure a value, or provider is specifically for this. But not sure how it would work given the dependency on $timeout.

1
  • 1
    Data sources are usually put into Services. So you could have a PersonService handling all logic related to storing/saving/searching/whatever Person objects. Commented Mar 8, 2014 at 0:27

2 Answers 2

2

You can create objects in a factory

 var Person = (function (params) {
    angular.extend(this, params);

    return {
        name: params.name,
    };

});

Person.create = function create(params) {
    return new Person(params);
};

myApp.factory('Person', function ($timeout) {
    return Person;
});

Then in your controller you can inject the factory and create Person objects.

myApp.controller('HomeCtrl', function($scope, Person) {
    $scope.person = Person.create({ name: 'Andy' });
});
Sign up to request clarification or add additional context in comments.

2 Comments

But how do I tell angular about the $timeout dependency?
You can inject it into the factory parameter function: myApp.factory('Person', function ($timeout) { your code });
0

I would make it a Service that returns a constructor.

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

myModule.service('Person', function($timeout) {
    // Actual person constructor defined once when
    // the service is first instantiated
    function Person(name) {
        this.name = name;

        this.start = function() {
            var that = this
            $timeout( function sayHello() {
                console.log(that.name);
                $timeout(sayHello, 1000);
            }, 1000);
        }                
    }

    this.create = function (name) {
        // Return a new instance
        return new Person(name);
    };
});

Note that you would use Person.create() to make instances in this case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.