2

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?

3
  • 2
    Wait, if I'm not mistaken $scope only exists inside a controller, whereas your code isn't. In that case it's not so strange $scope isn't defined. Commented Sep 15, 2013 at 16:48
  • i've posted this link in your previous question' page , have a look: plnkr.co/edit/uO9l7n?p=preview Commented Sep 15, 2013 at 16:50
  • @chemiv Yours seems like another implementation, with a lot more code though Commented Sep 15, 2013 at 16:55

1 Answer 1

6

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).

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

2 Comments

Thank you for the reply, but your fiddle still doesn't show the alert on page load, is something else missing?
@Jimmy yes, sorry about that, I've updated the fiddle. I had to add ng-app and use the built-in way of initializing angular.

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.