Monday, June 22, 2015

Value and Constant in AngularJS


Resource sharing in Global position is very common requirement in application development. In angular we have $rootScope service to share common object in global position. Beside $routeScope , we can use Values and Constants to share data from global position and can access from services/controller.

The purpose of Value and Constant  is same in AngularJS but the advantage of constant is that, we can inject this in configuration of module.
Let’s see each one of them with example.

Value :

<script>
        var myApp = angular.module('myApp', []);

        myApp.value('name', 'sourav kayal');

        //Inject value to controller      

        myApp.controller('myController', ['name', function (name) {
            console.log(name);
        }]);

    </script>

Here we have created “name” value and injected this to “myController”.  Now , we can access “name” to any controller/service as soon as we inject this.

We can set multiple property/complex model in value. Just like below.

   myApp.value('Address', {
            state: 'West Bengal',
            district : 'Howrah'
        });

As per our discussion, we cannot inject value in configuration of module. Therefore, it will throw error.

<script>
        var myApp = angular.module('myApp', []);

        myApp.value('name', 'sourav kayal');

        myApp.config(function (name) {
        });

    </script>


Constant :

Constant is very similar to value and the syntax is too same. Here we have defined Address constant and same is injected to controller.

<script>
        var myApp = angular.module('myApp', []);

        myApp.constant('Address', {
            state: 'West Bengal',
            district : 'Howrah'
        });

        myApp.controller('myController', ['Address', function (Address) {
            console.log(Address.state);
        }]);

</script>

We can inject constant to config of module. So this is valid.

<script>
        var myApp = angular.module('myApp', []);

        myApp.value('name', 'sourav kayal');

        myApp.constant('Address', {
            state: 'West Bengal',
            district : 'Howrah'
        });

        myApp.config(function (Address) {

        });
</script>

No comments:

Post a Comment