Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using $scope in Angular JS

    • 0
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 251
    Comment on it

    $scope is an object instance of a controller. $scope object instance is created when the ng-controller directive is called.

    The $scope object that is used by views is organized into a hierarchy. Firstly, there is a root scope, and then root scope can have one or more child scopes. Each view has its own $scope object which is a child of the root scope, so whatever variables one view controller sets on its $scope variable, those variables are invisible to other controllers.

    We can understand this by the example in the below code. Here we have two controllers named controller1 and controller2. In both the controllers we have a "data.var variable.

    Example:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    </head>
    
    <body ng-app="Myapp">
    
        <div ng-controller="controller1">
    
            {{data.var}}
    
        </div>
    
        <div ng-controller="controller2">
    
            {{data.var}}
    
        </div>
    
    
        <script>
            var app = angular.module("Myapp", []);
            var controller1 = app.controller("controller1", function($scope) {
                $scope.data = { var : "123456"};
            });
            var controller2 = app.controller("controller2", function($scope) {
                $scope.data = { var : "789455"};
            });
        </script>
    
    
    </body>
    </html>
    

    In the above example, there are two views each contain their own controller function. Each controller sets the variable data.var with two different values. When this code is executed the $scope object hierarchy will look like this: Root $scope 1.$scope for controller1 2.$scope for controller2

    As we can understand that $scope object created here is not the same object , there are two different $scope objects created for each controller. The two controller functions for the views set different values for the data.var variable in each of their own $scope object.

    So the first div HTML UI is binded with controller1 $scope instance and the second div HTML UI is binded with controller2 $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: