2

I am trying to iterate through local storage and add to a model within my controller.

angular.forEach(localStorage,function(value,key){
    $scope.cats.push(localStorageService.get(key));
});

However when I run this code I get

TypeError: Cannot set property 'cats' of undefined

I guess I am struggling to understand the concepts of scope in this.

5
  • I think you need to query localStorage to get the data first using localStorage.get('her is the key'); Commented Jul 31, 2013 at 4:02
  • You are correct in that part of the question is wrong, I have been messing a bit and did'nt change it back. I have edited the question. The original problem still persists though $scope is undefined. Commented Jul 31, 2013 at 4:16
  • Could you post the whole controller? Commented Jul 31, 2013 at 4:25
  • Can you add $scope.cats = [] before the forEach statement? You need to define it before use it for sure. And you need to pass $scope into you controller like function Ctrl($scope){...}. Just checking... Commented Jul 31, 2013 at 4:28
  • I fixed it using the context parameter. @sza yes I had defined $scope.cats already and it is there in the controller. Commented Jul 31, 2013 at 4:34

1 Answer 1

5

Fixed it like this:

angular.forEach(localStorage,function(value,key){
    this.push(localStorageService.get(key));
},$scope.cats);

Not sure if this is correct in the Angular way.

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

2 Comments

Yep. In the doc, it says the context is needed: angular.forEach(obj, iterator[, context]);
The brackets around the context parameter indicate that it's supposed to be optional.

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.