当从 Controller (父级)调用链接函数时,我们如何获得指令的特定隔离范围?
我有一个指令并使用 ng-repeat 重复它。每当单击指令模板中的按钮时,它将调用指令 Controller 中的函数 Stop(),该函数又调用父 Controller 中的函数 test(),在 test() 内它将调用指令链接函数中的方法 dirSample () .
当我在 dirSample() 中打印范围时,它会打印最后创建的指令的范围,而不是调用它的指令的范围。
如何获取调用它的指令的范围?
找到 pluker here
.directive('stopwatch', function() {
return {
restrict: 'AE',
scope: {
meri : '&',
control: '='
},
templateUrl: 'text.html',
link: function(scope, element, attrs, ctrl) {
scope.internalControl = scope.control || {};
scope.internalControl.dirSample = function(){
console.log(scope)
console.log(element)
console.log(attrs)
console.log(ctrl)
}
},
controllerAs: 'swctrl',
controller: function($scope, $interval)
{
var self = this;
self.stop = function()
{
console.log($scope)
$scope.meri(1)
};
}
}});
plunker 中的完整代码
最佳答案
由于您需要传递参数,因此我已将函数的绑定(bind)从 &
更改为 =
。这意味着一些语法更改是有序的,如果您想在最后一直拥有它,您还需要沿着链传递范围:
HTML:
<div stopwatch control="dashControl" meri="test"></div>
Controller :
$scope.test = function(scope)
{
console.log(scope);
$scope.dashControl.dirSample(scope);
}
指令:
.directive('stopwatch', function() {
return {
restrict: 'AE',
scope: {
meri : '=',
control: '='
},
templateUrl: 'text.html',
link: function(scope, element, attrs, ctrl) {
scope.internalControl = scope.control || {};
scope.internalControl.dirSample = function(_scope){
console.log(_scope);
}
},
controllerAs: 'swctrl',
controller: function($scope, $interval)
{
var self = this;
self.stop = function()
{
console.log($scope);
$scope.meri($scope);
};
}
}});
关于javascript - 如何使用 ngrepeat 和双向绑定(bind)获取指令的隔离范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29555509/