Search code examples
javascriptangularjsiife

Not accessible constant value in other controller in angular js using IIFE function


following is my sample angular js code, i have declared myApp module, i want to write code in two different file , in first file i have declared module and one constant file and in other file i have declared controller. and i want to access constant value of CLientId into controller, but it is not accessible please provide solution

<div ng-app="myApp" ng-controller="myCtrl as vm">
{{ vm.firstName + " " + vm.lastName + " "+ vm.getName(); }}
</div>

<script>
// i want to diclare above code into different js files
//app.js 
(function(){

angular.module("myApp", []).value('clientId', 'a12345654321x');

})();

//con.js 
(function(){
angular.module("myApp", []).controller("myCtrl", function(clientId) {

    this.firstName = "John";
    this.lastName = "Doe";
    this.getName= name;
    function name()    {
        return  clientId ; 
     }
});

})();

</script>

</body>
</html>

Solution

  • The controller registration should not have [] brackets as it will overwrite the already created module. Do it like this:

    (function(){
    angular.module("myApp").controller("myCtrl", function(clientId) {
    
        this.firstName = "John";
        this.lastName = "Doe";
        this.getName= name;
        function name()    {
            return  clientId ; 
         }
    });
    
    })();