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

时间:2015-06-19 10:00:03

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-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
}

1 个答案:

答案 0 :(得分:2)

您想要在指令控制器中访问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