1

I am new to Javascript and Angular and am a bit confused as to how the below code is executing:

angular.controller('TestController',function($scope){
    $scope.counter = {clicks:0};
    $scope.count = function(){
        $scope.clicks += 1;
    }
});

I am able to write $scope.clicks += 1 and the count increases correctly by 1. Isn't counter a Javascript object and dont we have to write it as $scope.counter.clicks += 1?

2 Answers 2

1

You are correct. It IS a javascript object and you should be writing $scope.counter.clicks += 1 if this is the variable you want to increment.

I assume you are binding with {{clicks}} and therefore you think it is working correctly, but it isn't (this is a different property on the scope). You should be binding {{counter.clicks}} to see the "real" value.

You can write a console.log line inside the count() function to see the true value of $scope.counter.clicks and check for yourself.

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

1 Comment

You are right. I had to bind $scope.counter.clicks with {{counter.clicks}} to actually see it working. Thanks for your help!
1

Scope is the area in which your functions are executing. Json is a different language than JavaScript and angular is a js framework. You are simply counting a click. Your code is working properly.

1 Comment

@Oriol he originally stated json in his question please un down arrow thanks

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.