0
$scope.post1 = angular.fromJson(window.localStorage['like'] || '{}');

  var like ={
    id:''+id
  };
  $scope.post1.push(like);

window.localStorage['like'] = angular.toJson( $scope.post1);

When I run this code it gives $scope.post1.push is not a function..How to solve this problem?

3
  • check the return type of window.localstorage. that should give you some clues. Use angular.isArray(window.localstorage['like']); Commented Apr 29, 2015 at 8:01
  • Object doesn't have push method, only array does. Commented Apr 29, 2015 at 8:04
  • In case post1 not being an array isn´t the problem you could try to put a $timeout after reading from local storage. It could be a matter of race conditions. $timeout(function(){$scope.post1.push(like);},200); Commented Apr 29, 2015 at 8:09

1 Answer 1

1

There is no push() function in javascript Object or String. But Array has it.

Maybe you could do something like this instead:

$scope.post1.like = { id: '' + id };

See https://docs.angularjs.org/api/ng/function/angular.fromJson for more information about angular.fromJson() return type.

Edit:

It seems like I misread something. Try this:

http://plnkr.co/edit/PXNul5c9FbKNHxhQZjEF

If you want to create array of object, you should pass array to angular.fromJson()

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

2 Comments

i want to make array of objects
simple,make post1 an array and push objects in it.

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.