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?

2
  • 1
    What do you mean with a global variable? Commented Sep 26, 2015 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 stackoverflow.com/questions/14049480/… for a more in depth analysis of this and potential solutions. Commented Sep 26, 2015 at 14:12

1 Answer 1

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.

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

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.