payal arora payal arora - 1 month ago 5
Javascript Question

$scope is undefined in angular js app

{% load staticfiles %}

<html ng-app="myBlog">
<head>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
--> <script type="text/javascript" src="{% static 'js/libs/angular.min.js' %}"></script>
<!-- <script type="text/javascript" src="{% static 'js/modules/app.module.js' %}"></script>
<script type="text/javascript" src="{% static 'js/modules/app.config.js' %}"></script> -->
<!-- <script type="text/javascript" src="{% static 'js/modules/blog-list.module.js' %}"></script>
--> <script type="text/javascript" src="{% static 'js/controllers/blog-list.js' %}"></script>
</head>

<body>
<input type="text" ng-model="name">
<p>hi , {{name}}</p>

<div ng-controller="Controller">
<h1>{{title}}</h1>
<button ng-click="someTest()">click</button>
</div>
</body>
</html>


here is the controller

'use strict'

var blogList = angular.module('myBlog' , []);

blogList.controller('Controller', ['$scope', function($scope){

$scope.clicks="";

console.log("he");
$scope.title = 'Hi there';
$scope.clicks = 0;
console.log($scope)

$scope.someTest = function(){
console.log($scope)
console.log("there")
$scope.clicks +=1;
$scope.title = 'Clicked' + clicks;
};
}]);


When the button is clicked it gives the error


angular.min.js:118 ReferenceError: clicks is not defined at
b.$scope.someTest (blog-list.js:16) at fn (eval at compile
(angular.min.js:233), :4:215) at b (angular.min.js:126) at
e (angular.min.js:276) at b.$eval (angular.min.js:145) at b.$apply
(angular.min.js:146) at HTMLButtonElement.
(angular.min.js:276) at Sf (angular.min.js:37) at HTMLButtonElement.d
(angular.min.js:37)


How can i get rid of the error ..thank in advance

Answer

You have used $scope.title = 'Clicked' + clicks;.You missed to refer to the $scope when you have used the clicks. Change it to $scope.title = 'Clicked' + $scope.clicks; So says your error:

ReferenceError: clicks is not defined at b.$scope.someTest

$scope.someTest = function(){
     console.log($scope);
     console.log("there");
     $scope.clicks += 1;
     $scope.title = 'Clicked' + $scope.clicks;
};
Comments