Pass variable from directive to controller

2.2k Views Asked by At

I have this directive definition and want to pass currentScriptPath to the TestController.

How do I do that?

(function(currentScriptPath){
    angular.module('app', [])
        .directive('test', function () {
            return {
                restrict: 'E',
                scope: {},
                templateUrl: currentScriptPath.replace('.js', '.html'),
                replace: true,
                controller: TestController,
                controllerAs: 'vm',
                bindToController: true
        };
    });
})(
    (function () {
        var scripts = document.getElementsByTagName("script");
        var currentScriptPath = scripts[scripts.length - 1].src;
        return currentScriptPath;
    })()
);

TestController.$inject = ['$scope'];

function TestController($scope) {
    // try to access $scope.currentScriptPath here
}
1

There are 1 best solutions below

8
Pankaj Parkar On BEST ANSWER

As you want to access currentScriptPath in your directive controller. You need to only attach that variable into your current scope inside link function of directive & that scope would be make currentScriptPath available to you controller TestController scope because you have used bindToController: true, in your directive.

Markup

<div ng-controller="Ctrl">
    <test></test>
</div>

Directive

(function(currentScriptPath) {
    angular.module('app', [])
    .directive('test', function() {
      return {
        restrict: 'E',
        scope: {},
        templateUrl: currentScriptPath.replace('.js', '.html'),
        replace: true,
        controller: TestController,
        controllerAs: 'vm',
        bindToController: true,
        link: function(scope, element, attrs) {
          scope.currentScriptPath = currentScriptPath; //will update the value of parent controller.
        }
      };
    });
})(
  (function() {
    var scripts = document.getElementsByTagName("script");
    var currentScriptPath = scripts[scripts.length - 1].src;
    return currentScriptPath;
  })()
);

Controller

function TestController($scope, $timeout) {
  var vm = this;
  $timeout(function() {
    alert($scope.currentScriptPath) //gets called after link function is initialized
  })
}

Demo Plunkr