Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将变量从指令传递到控制器_Javascript_Angularjs_Angularjs Directive_Angularjs Scope_Angularjs Controller - Fatal编程技术网

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

Javascript 将变量从指令传递到控制器,javascript,angularjs,angularjs-directive,angularjs-scope,angularjs-controller,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,Angularjs Controller,我有这个指令定义,希望将currentScriptPath传递给TestController 我该怎么做 (function(currentScriptPath){ angular.module('app', []) .directive('test', function () { return { restrict: 'E', scope: {}, t

我有这个指令定义,希望将
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
函数内的当前作用域中&该作用域将成为控制器
TestController
作用域,因为您在指令中使用了
bindToController:true,

标记

<div ng-controller="Ctrl">
    <test></test>
</div>
控制器

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

那不行<代码>$scope.currentScriptPath在控制器中未定义
currentScriptPath
不是用于绑定的变量。我不想将publish
currentScriptPath
用作DOM绑定的属性。我只想将其用作控制器的参数。@Alex您没有发布该值,因为您想将修改后的值发送给控制器。。您需要使用此方法..查看更新的代码..您需要为其使用链接功能
$scope.currentScriptPath
仍然
未定义
。我不想更新父控制器值。我想将值传递到指令的控制器中。为了更好地理解,我将控制器添加到问题中。
function TestController($scope, $timeout) {
  var vm = this;
  $timeout(function() {
    alert($scope.currentScriptPath) //gets called after link function is initialized
  })
}