2

I need to assign department to an employee in angularJS application. I created API resource on server side which returns JSON array of possible values.

[
  {"id":0,"name":"human resources"},
  {"id":1,"name":"public relations"},
  {"id":2,"name":"development"}
]

And my Employee resource works with IDs of department, like so..

{
  employeeId: 1,
  firstName: "Adam",
  lastName: "Abrons",
  departmentId: 2
}

I want to use those values in angular filter for viewing employee and for ngOptions directive for editing employee.

Since those enum values are pretty much stable, how do I load them once and keep them on client side until user leaves the website?

Peracek
  • 1,801
  • 1
  • 15
  • 17
  • I personally use enum from mongoose schema, http://mongoosejs.com/docs/api.html#schema_string_SchemaString-enum – YOU Apr 08 '15 at 15:10
  • You load them and store the http promise in a variable of a service. You get this promise from the service every time you need it. – JB Nizet Apr 08 '15 at 15:10
  • I've used html localStorage for this kinda thing before, however you can also use angular.js cache: http://stackoverflow.com/questions/14117653/ – Ruslan Apr 08 '15 at 15:10

1 Answers1

1

You can use the build it cache feature in $http module

$http.get('/api/enums', {cache: true}).success(function(enums){
});

In addition, you can also wrap it up as a service

angular.module('app').service('enumService', function ($http) {

    return {
        getEnums: getEnums
    };

    function getEnums(){
        return $http.get('/api/enums', {cache: true});
    }
});

Other way using a promise (credit to JB Nizet's comment)

angular.module('app').service('enumService', EnumService);

function EnumService($http) {

    var getEnumsPromise = $http.get('/api/enums');

    return {
        getEnums: getEnums
    };

    function getEnums(){
        return getEnumsPromise;
    }
}
Community
  • 1
  • 1
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
  • You could simply use `var result = $http.get('/api/enums');`, and return this result from `getEnums()` – JB Nizet Apr 08 '15 at 15:29