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