Search code examples
javascriptjqueryangularjs

How to use AngularJS $scope?


I have a paragraph and a counter. I want to update the counter when someone clicks on the paragraph using AngularJS. I wrote the following code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>
<body>

<p>Click on this paragraph.</p>

<div ng-app="myApp" ng-controller="myCtrl">

<h2>{{ count }}</h2>
</div>
<script>
var $ang;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $ang=$scope;
    $ang.count=10;
});
$(document).ready(function(){
    $("p").click(function(){
        console.log("The paragraph was clicked.");
        $ang.count=$ang.count-1;
    });
});
</script> 
</body>
</html>

But it's not working. I guess I'am using $scope in a wrong way but I am not sure how to fix it.


Solution

  • You had several errors in your code. I've refactored it a bit. Make sure to use ng-app and ng-controller properly. Do not use jquery in combination with angular. You can observe scope changes with the $watch function - this method is expensive in terms of computation and should not be overused.

    <!DOCTYPE html>
    <html ng-app="myApp">
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    
    </head>
    <body>
    
    <div ng-controller="myCtrl">
        <p ng-click="onClick()">Click on this paragraph.</p>
    
        <h2>{{ count }}</h2>
    </div>
    
    </div>
    <script>
    
    
    angular
        .module('myApp', ['ng'])
    
        .controller('myCtrl', function($scope) {
            $scope.count = 10
            $scope.onClick = function () {
                $scope.count--
            }
    
            // this is how you can observe state
            // changes outside of event handlers
            $scope.$watch('count', function(newValue, oldValue) {
                console.log("The paragraph was clicked.")
            })
        })
    </script>
    </body>
    </html>