1

I have an AngularJS service that looks like this:

angular.module('myModule', [])
  .factory('$myService', function () {    
    return {
      getName: function () {
        return 'Bill';
      },

      isAvailable: function () {
        return true;
      }
    };
  })
;

Is there a way to add properties? Currently, the service has function (aka $myService.isAvailable()). I'm curious, is there a way to have something like $myService.someProperty? If so, how? Or, does everything in a service have to be a function?

Thank you!

1
  • Please consider removing the $ prefix if possible, it is reserved for anything built-in from angularjs. Commented Aug 15, 2014 at 6:33

2 Answers 2

2

When you use the Revealing Module Pattern, you can easily encapsulate your data and expose only the properties/functions that you want in your public API:

angular.module('myModule', [])
  .factory('$myService', function () {   
    var name = { name: 'John' };
    var phone = { phone: '555-5555'};
    var SSN = 123456789;
    var address = '5555 Rd Blvd.';
    var available = { isAvailable: false };

    return {
      getName: function () {
        return name;
      },

      isAvailable: function () {
        return available;
      }

      name: name,
      phone: phone,
      address: address
    };
  })
;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for showing me the "Revealing Module Pattern". This approach allowed me to get through JSHint.
2

Yes, you can simply add a property in the returned object

angular.module('myModule', [])
  .factory('$myService', function () {    
    return {
      getName: function () {
        return 'Bill';
      },

      isAvailable: function () {
        return true;
      },

      someProperty: 'New Property'
    };
  });

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.