Search code examples
angularjsangularjs-directiveangularjs-scope

How to access app.controller $scopes inside app.directive


Ok i have the following angular js code. What im trying to do is to set some scopes to null when enter button is pressed inside a form. So far I have div with ng-click event that sets these scopes to null, but i want to make the same with enter key also.

App directive:

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                //access scopes here like that
                //$scope.eurval = null;
              //$scope.usdval = null;
              //$scope.otherval = null;
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

App.controller

app.controller('formCtrl', function($scope) {
              $scope.eurval = null;
              $scope.usdval = null;
              $scope.otherval = null;
});

Solution

  • Have a method that will do that for you:

    app.controller('formCtrl', function($scope) {
        $scope.reset = function() {
            $scope.eurval = null;
            $scope.usdval = null;
            $scope.otherval = null;
        };
    
        $scope.reset();
    });
    

    Then use it inside the directive:

    if(event.which === 13) {
        scope.$apply(function (){
            scope.reset();
            scope.$eval(attrs.ngEnter);
        });
        event.preventDefault();
    }