将变量从指令传递到控制器

Pass variable from directive to controller

我有这个指令定义,想将 currentScriptPath 传递给 TestController

我该怎么做?

(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
}

因为你想在指令控制器中访问 currentScriptPath。您只需要将该变量附加到指令的 link 函数内的当前范围内,并且该范围将使 currentScriptPath 可用于您的控制器 TestController 范围,因为您已经使用了 bindToController: true,在你的指令中。

标记

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

指令

(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;
  })()
);

控制器

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

Demo Plunkr