Saturday, 22 December 2018

How to use AngularJS Scope


AngularJS Scope ($scope)

Scope is an object that refers to the application to binding between the HTML and controller. The application can have multiple scopes, because directives can create new child scopes. When new scopes are created, they are added as children of their parent scope.



Example

<!DOCTYPE html>
<html >
<head>
    <title>AngualrJS $scope object</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
    <script src="//code.angularjs.org/1.2.20/angular-sanitize.min.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="empController">
        <h1>welcome to :  {{wibsite}} </h1>
        <input type="text" ng-model="wibsite" />
    </div>
    <script>
        var myApp = angular.module('myApp', []);
        myApp.controller('empController', function ($scope) {
            $scope.wibsite = "code-view.com !";       
        });
    </script>
</body>
</html>

Root Scope ($rootScope)
There will be a single root scope in application. All other scopes is created in application is sub scopes of the root scope. Scopes provide separation between the view and the model.

<!DOCTYPE html>
<html>
<head>
    <title>AngualrJS Controller</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
    <script src="//code.angularjs.org/1.2.20/angular-sanitize.min.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="mainController">
        Name: {{controllerName}} <br />
        Message: {{message}} <br />

        <div style="margin:20px 0 20px 20px;" ng-controller="subController">
        Name: {{controllerName}} <br />
        Message: {{message}} <br />
        </div>
    </div>

    <div ng-controller="siblingController">
        Name: {{controllerName}} <br />
        Message: {{message}} <br />
    </div>
    <script>
        var myApp = angular.module('myApp', []);

        myApp.controller('mainController', function ($scope, $rootScope) {
            $scope.controllerName = "mainController";
            $rootScope.message = "welcome to code-view.com!";
        });

        myApp.controller('subController', function ($scope) {
            $scope.controllerName = "subController";
        });

        myApp.controller('siblingController', function ($scope) {

        });
    </script>
</body>
</html>