Angular Scope inside script

All we need is an easy explanation of the problem, so here it is.

Can we use the angular variables defined in scope inside script tag like below.

HTML CODE:

<div ng-controller="AngularCtrl">
 <script>
  alert($scope.user_name);
 </script>
</div>

JS CODE:

function AngularCtrl($scope){
 $scope.user_name = 'John';
}

I just get ‘$scope is not defined’. Can someone help me with what i am doing wrong here?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

No you can’t. $scope is only defined inside Angular, i.e. within your AngularCtrl-function. There are ways to get access to angular scopes from the outside, but that’s usually bad practice and a sign that you’re not using Angular correctly.

A more angulariffic way to do what you’re trying is to make the alerting a part of the controller-logic:

function AngularCtrl($scope) {

    $scope.user_name = 'John';

    $scope.sayHi = function(){
        alert('Hi ' + $scope.user_name);
    }
}

You can then use a variety of angular-techniques (Demo Here) to call that sayHi() function. Some examples:

In response to a click

<div ng-click="sayHi()">Demo clickable - Please click me</div>

Automatically once when a given element is created/initialized

<div ng-init="sayHi()">Demo ng-init</div>

Directly from the controller when it is initialized

function AngularCtrl($scope) {

    $scope.user_name = 'John';

    $scope.sayHi = function(){
        alert('Hi ' + $scope.user_name);
    }

    // Call it
    $scope.sayHi();
}

Hopefully these examples are inspiring, but what you really should do depends on what you are really trying to accomplish.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply