1

I have global variable $scope.posts in controller Angular JS: I do increment this variable:

$scope.posts = $scope.posts + 1;

So my IDE editor underlines this code and tells:

Value assigned to primitive wil be lost

What is mean and how to fix?

Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81
Muhad
  • 283
  • 1
  • 5
  • 14
  • 1
    What do you mean with a global variable? – Wawy Sep 26 '15 at 13:45
  • `posts` is a primitive (non-object) property of `$scope` in this instance, but being assigned to `$scope` **does not** make the property ***global***. Your IDE is likely warning you that you are overwriting this property in another controller, but without more code, that can't be confirmed. See http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs for a more in depth analysis of this and potential solutions. – Claies Sep 26 '15 at 14:12

1 Answers1

4

Init the variable

In your app.js or main Angular module init the variable with this

.run(function ($rootScope) {
    $rootScope.posts;
})

Then anywhere you want to increase this use the syntax

$scope.posts += 1;

It increments the value by one.

Best Practice

$rootScope is probably not what you want. You can share data across your app with a service or a factory. I've made a small Gist to show how this works, check it out here.

Community
  • 1
  • 1
Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81