Jimmy
Jimmy

Reputation: 12487

AngularJS onload - Uncaught ReferenceError: $scope is not defined

I am playing around with different ways of loading an alert on load with angularJS. I saw this method documented:

http://jsfiddle.net/AQ533/9/

JS

$scope.init = function () {
  ($window.mockWindow || $window).alert('Hello');
};

HTML

<div data-ng-controller="myCtrl" data-ng-init="init()">
<span id="logo">Just a</span><span id="small" >PREVIEW</span>    
</div>

I get the following error:

Uncaught ReferenceError: $scope is not defined

Can anyone tell me what I am doing wrong with this implementation please?

Upvotes: 2

Views: 7774

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

You must define myCtrl in order to have $scope available:

function myCtrl($scope, $window) {
    $scope.init = function () {
      ($window.mockWindow || $window).alert('Hello');
    };
}

Here is an updated fiddle.

Edit: I had to wrap your fiddle with a div that included ng-app. ng-app tells angular where the global scope of the application is. This allows it to compile everything inside and see if it can find any controllers etc.

Also, $scope must be passed in to the implementation of controller myCtrl with any dependencies afterward (in this case $window service).

Upvotes: 6

Related Questions