Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new Angular $resource with default values?

It is possible to define an Angular $resource that has always the same default values on creation with new()?

For example if I have the following resource definition:

var Drawer = $resource('/drawer/:drawerId', { drawerId: '@id'});

And the Drawer object needs to have a "socks" property that I want to be always initialized as an empty array [], and maybe some others like 'timesOpened' to 0, or things like that.

The only way to do this would be like:

var newDrawer = new Drawer({ socks: [], timesOpened: 0});

I was thinking about defining in the same service I have for my resource (let's call it drawerService) a default/initialization object like this:

defaultDrawer = { socks: [], timesOpened: 0};

And then when creating the resource:

//New drawer with defaults
var newDrawer = new drawerService.Drawer(drawerService.defaultDrawer);
//New drawer with defaults and some other initialization
var anotherDrawer = new drawerService.Drawer(angular.extend(drawerService.defaultDrawer, {material: 'plastic'});

Is this the only way of doing it?

like image 794
John Bernardsson Avatar asked May 26 '15 15:05

John Bernardsson


1 Answers

You are correct, there is no easy way to do this; it is not a supported functionality in Angular. A cleaner way that you might do this is by creating a Drawer factory in your drawerService. It might look something like this:

angular.module('app').factory('drawerService', function() {

    var Drawer = $resource('/drawer/:drawerId', { drawerId: '@id'});

    function drawerFactory(options) {
        var defaults = {
            socks: [],
            timesOpened: 0
        };
        options = angular.extend(defaults, options || {});
        return new Drawer(options);
    }

    return {
        Drawer: Drawer,
        create: drawerFactory
    };
});

This would allow you to create a new Drawer like so:

//New drawer with defaults
var newDrawer = drawerService.create();
//New drawer with defaults and some other initialization
var anotherDrawer = drawerService.create({material: 'plastic'});

It's still not ideal, but it is slightly cleaner and the least evil way I can think of accomplishing what you are trying to accomplish.

like image 190
kanzelm3 Avatar answered Nov 16 '22 22:11

kanzelm3