2

I have a service "MyService" that contains the following:

this.myobj = {'dog': 'bark', 'cat': 'meow'}

I inject this service into a directive. Within the directive link function I have a $scope.$destroy that does the following:

console.log(MyService.myobj);
delete MyService.myobj.dog;
console.log(MyService.myobj);

The console.log output looks like after the delete still shows up as:

{'dog': 'bark', 'cat': 'meow'}

Even though I called the delete on the 'dog' key. What is going on? Is there a more proper way to delete the key?

1 Answer 1

3

Add a method to the service that deletes it's properties:

var myObj = {
dog: 'bark',
cat: 'meow',
delKey: function (keyName) {
    delete this[keyName];
    }
}

Then call the method:

MyService.myobj.delKey('dog');

If you want to have a method assigned to that service which can operate on any object within that service:

myObj: {
            dog: 'bark',
            cat: 'meow'
        },
delKey: function (obj, key) {
            delete this[obj][key];
        }

you can check out this plnkr:

http://plnkr.co/edit/f0ousH69sAm3Kdr36kNJ

Sign up to request clarification or add additional context in comments.

2 Comments

Just by way of best practices, I believe this is more appropriate for angular. You want to maintain a pretty high level of abstraction. A service should operate on itself by it's own methods, which can then be called by anyone who needs them. Came across this on a similar post, if it might be useful: perfectionkills.com/understanding-delete
The problem with this is I don't want delKey within myObj as myObj is a part of the service. Ideally if there was a MyService.delKeyFromMyObj('dog') that could do the same, that would be more desirable.

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.