0

Good day mate, i just want to ask how can i use a function from my controller inside my custom directive?

the scenario is a have a directive that's restrict the panel views for different user so i need to construct a function that's evaluate the user. i want to declare that function in a controller so i can use it to another controllers and the same time with directives too.

//my directive: 

app.directive("restricted", function() {
     return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            // Some auth check function
            var isAuthorized = checkAuthorization();
            if (!isAuthorized) {
                element.css('display', 'none');
            }
        }
    }
})

//my function inside controller
app.controller('myController', ['$scope', function() {

    $scope.checkAuthorization = function() {
           //Code here. . .
    }

})];

thanks guys

georgeawg
  • 48,608
  • 13
  • 72
  • 95
cute_programmer
  • 332
  • 3
  • 13
  • https://stackoverflow.com/questions/16839259/angular-calling-controller-function-inside-a-directive-link-function-using You should search a bit more before asking question. Passing a function in parameters seems to be the more natural way. You can pass multiple function by passing a JSON containing multiples functions. Also consider declaring you functions in a factory or service if you want to use it in another controller. – Alburkerk Jun 09 '17 at 03:41
  • Directives should only be calling parent controllers to communicate events. Visibility of a directive should be controlled by a Model value created by the Controller. In that case, use the [ng-show directive](https://docs.angularjs.org/api/ng/directive/ngShow). – georgeawg Jun 09 '17 at 04:20

0 Answers0