javascript - AngularJS onload - Uncaught ReferenceError: $scope is not defined - Stack Overflow

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

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

/

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?

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

http://jsfiddle/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?

Share Improve this question asked Sep 15, 2013 at 16:42 JimmyJimmy 12.5k29 gold badges114 silver badges205 bronze badges 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. – 11684 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 – Ivan Chernykh Commented Sep 15, 2013 at 16:50
  • @chemiv Yours seems like another implementation, with a lot more code though – Jimmy Commented Sep 15, 2013 at 16:55
Add a ment  | 

1 Answer 1

Reset to default 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 pile 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).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742285665a4415274.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信