SEARCH BY

All

  • All
  • Java8
  • Spring

scope in AngularJS

Post a Comment

Introduction to scope

Scope is a build in object in AngularJS represented as $scope, which is passing as a parameter to controller() function. Scope is holding data, which is passing to HTML view blocks.

Scope data can be accessible via AngularJS expressions, ng-model or ng-bind attributes.

ng-model is a two way data transformer between controller and view.

 <div ng-controller="myc">
        Enter You Name:<input name="uname" ng-model="name"/>
        <hr>
        Your name is : {{name}}
        <hr>
        Hi <b ng-bind="name"></b> How are you doing.
    </div>
var appRoot=angular.module("cookiestore_app",[]);
(function() {
    'use strict';

   appRoot
        .controller('myc', ControllerController);

    ControllerController.$inject = ['$scope'];
    function ControllerController($scope) {
        var vm = this;
        $scope.name="Jai";

    }
})();
Output

Objects with $scope

Here i sill show you how to store object in $scope and how to use that object in a view or controller linked HTML code block.


$scope.person = {
            "name": "Elupuru Jaya Kumar reddy",
            "Phone": "9494291913"
        }

 {{person.name}} 
 {{person.Phone}}
 
 <b ng-bind="person.name"></b>

$rootScope

Data attached to $rootScope is available to all intiated controllers

    <div ng-controller="father">
        My Name is <b ng-bind="fatherName"></b>, Following are my family member names;
        <div ng-controller="kid">
            Hi iam <b ng-bind="kidName"></b>, Iam son of <b ng-bind="fatherName"></b>
        </div>
    </div>
    <div ng-controller="mother">
        Hi iam <b ng-bind="motherName"></b>, Iam wife of <b ng-bind="fatherName"></b>
    </div>
(function () {
    'use strict';

    appRoot
        .controller('father', ControllerController);

    ControllerController.$inject = ['$scope', '$rootScope'];
    function ControllerController($scope, $rootScope) {
        var vm = this;

        $rootScope.fatherName = "Ganguly";

    }
})();

(function () {
    'use strict';

    appRoot
        .controller('kid', ControllerController);

    ControllerController.$inject = ['$scope'];
    function ControllerController($scope) {
        var vm = this;

        $scope.kidName = "Druv";

    }
})();

(function () {
    'use strict';

    appRoot
        .controller('mother', ControllerController);

    ControllerController.$inject = ['$scope'];
    function ControllerController($scope) {
        var vm = this;
        $scope.motherName = "Veena";

    }
})();
Output
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox