Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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="http://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> 

share|improve this question
up vote 6 down vote accepted

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.

share|improve this answer
1  
Thanks a lot VVK it works – vimuth Dec 16 '15 at 6:08
    
Thanks a lot, I was scratching my head for ages and this was the missing link (you need bind data between the directive and parent controller via the attribute) – Tahir Khalid Jun 18 at 11:48
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
                }
             };
        });
share|improve this answer
1  
Thanks a lot "vijay shegokar". – vimuth Dec 16 '15 at 6:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.