[英]Pass variable from directive to controller
I have this directive definition and want to pass currentScriptPath
to the TestController
. 我有此指令定义,并希望将
currentScriptPath
传递给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
}
As you want to access currentScriptPath
in your directive controller. 如要在指令控制器中访问
currentScriptPath
。 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. 您只需要将该变量附加到指令的
link
函数中的当前作用域中,该作用域将使currentScriptPath
可用于您的控制器TestController
作用域,因为您已在指令中使用bindToController: true,
。
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
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.