nickponline
nickponline

Reputation: 25914

Where do you declare objects in AngularJS?

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.

Upvotes: 1

Views: 173

Answers (2)

David East
David East

Reputation: 32614

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

Upvotes: 2

acjay
acjay

Reputation: 36571

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.

Upvotes: 0

Related Questions