Muhad
Muhad

Reputation: 283

Increment variable in Angular JS?

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?

Upvotes: 1

Views: 1386

Answers (1)

Joe Lloyd
Joe Lloyd

Reputation: 22323

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.

Upvotes: 4

Related Questions