krs
krs

Reputation: 178

(angularjs) getting 'ReferenceError: $scope is not defined' when injecting controller

I have am trying to learn AngularJS. I have a HTML page where I am trying to inject module but getting an error

The main js file:

var classificationModule = angular.module('mainapp',[]);

classificationModule.controller('firstcontroll',function(){
    $scope.text="Goodday"
});

The HTML PAGE:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta name="layout" content="main"/>
    <title>Classification Toolkit for Grails</title>          

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js"></script>
    <asset:javascript src="main.js"/>        

</head>
<body >   
    <div ng-app='mainapp' ng-controller='firstcontroll'>
        Hello, {{text}}
    </div>   

</body>
</html>

Getting the following error :

ReferenceError: $scope is not defined

I dont know what I am doing wrong.

Upvotes: 2

Views: 12252

Answers (2)

Tony
Tony

Reputation: 1140

Try passing $scope in the function.

var classificationModule = angular.module('mainapp', []);

classificationModule.controller('firstcontroll', function($scope) {
  $scope.text = "Goodday"
});
<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <meta name="layout" content="main" />
  <title>Classification Toolkit for Grails</title>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js"></script>
  <asset:javascript src="main.js" />

</head>

<body>
  <div ng-app='mainapp' ng-controller='firstcontroll'>
    Hello, {{text}}
  </div>

</body>

</html>

Upvotes: 3

Tiborg
Tiborg

Reputation: 2305

You should write

var classificationModule = angular.module('mainapp', []);

classificationModule.controller('firstcontroll', function($scope) {
  $scope.text = "Goodday"
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='mainapp' ng-controller='firstcontroll'>
  Hello, {{text}}
</div>

$scope is a variable provided by angular JS' dependency injection system, and basically it works by matching providers to named parameters.

Upvotes: 1

Related Questions