Access AngularJs directive variable inside controller

All we need is an easy explanation of the problem, so here it is.

I’m little bit new to Angularjs. What I want is access “$scope.myVar” variable inside ‘myController‘ controller. It would be great help if you can provide a solution.

angular.module('myDirective', [])
        .controller('myController', ['$scope', function ($scope) {
               
            }])
        .directive('myDirective', function () {           
            return {
                scope: {
                    myVar: '='                  
                },
                controller: function ($scope) {  
                    $scope.myVar = 'xyz';
                    alert($scope.myVar);
                }
            };
        });
<html lang="en-US">  
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script type="text/javascript" src="newjavascript.js"></script>
    <body ng-app="myDirective">   
        <div ng-controller="myController">
            <my-directive></my-directive>>
        </div>
    </body>
</html> 

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You just create a myVar variable in your controller and pass it to the directive using my-var attribute.

In your myController, Define myVar as

$scope.myVar= "Hello"

I your DOM, pass it to the directive as

<my-directive my-var="myVar"></my-directive>

Since you are using two way binding, any changes made to myVar by the directive are available in your controller.

You can put a watch on myVar to track the changes.

Method 2

angular.module('myDirective', [])
        .controller('myController', ['$scope', function ($scope) {
               $scope.show = function() {
                   alert($scope.myVar);
               }; 
            }])
        .directive('myDirective', function () {           
            return {
                scope: {
                    myVar: '='                  
                },
                controller: function ($scope) {  
                    $scope.myVar = 'xyz';
                    alert($scope.myVar);
                    $scope.$parent.myVar = $scope.myVar; // here you can access the controller scope by using $parent
                }
             };
        });

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply