Javascript 将回调绑定到没有独立作用域的指令
将回调函数绑定到指令时,使用正确的上下文执行此函数对我来说很重要。现在,只要指令有一个独立的作用域,它就不是问题Javascript 将回调绑定到没有独立作用域的指令,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,将回调函数绑定到指令时,使用正确的上下文执行此函数对我来说很重要。现在,只要指令有一个独立的作用域,它就不是问题 <bar-foo callback="mycontroller.callback()"></bar-foo> 在没有独立作用域的情况下,我从$attrs attrubute提取回调 $scope.callback = $parse($attrs.callback)($scope); 但是,现在我做不到 <bar-foo callback="myco
<bar-foo callback="mycontroller.callback()"></bar-foo>
在没有独立作用域的情况下,我从$attrs attrubute提取回调
$scope.callback = $parse($attrs.callback)($scope);
但是,现在我做不到
<bar-foo callback="mycontroller.callback()"></bar-foo>
因为它将直接执行回调。解决这个问题的首选方法是什么
首先在控制器中创建一个函数,该函数在该函数内部显式设置该的值:
this.exportableCallback = this.callback.bind(this);
this.exportableCallback = function() {
console.log(arguments);
}.bind(this);
其中this.callback
是用于隔离作用域的回调
第二步是将其设置为属性
<hello-world callback="mycontroller.exportableCallback"></hello-world>
如果要将参数传递到此函数,请执行以下操作:
this.exportableCallback = this.callback.bind(this);
this.exportableCallback = function() {
console.log(arguments);
}.bind(this);
因为这个范围不是孤立的,所以不只是调用你想要的吗
.directive('helloWorld', function () {
return {
restrict: 'E',
template: '<button ng-click="mycontroller.callback()">Not isolated</button>',
}
});
指令('helloWorld',函数(){
返回{
限制:'E',
模板:“未隔离”,
}
});
然后打电话给你的指令
<hello-world></hello-world>
还是我在这里遗漏了什么??还需要使用require属性指定控制器。在没有作用域的指令中,只需访问指令模板中的mycontroller.callback()
.directive('helloWorld', function () {
return {
restrict: 'E',
scope: false,
//Use THIS
template: '<button ng-click="mycontroller.callback()">Not isolated</button>',
//NOT this
//template: '<button ng-click="callback()">Not isolated</button>',
controller: function ($attrs, $scope, $parse) {
//$scope.callback = $parse($attrs.callback)($scope);
}
}
});
单击指令的元素时,由回调
属性定义的角度表达式将使用作为$event
公开的事件对象进行计算
有关
$event
的更多信息,请参阅。如果要重用该指令,该怎么办?如果要重用该指令,该怎么办?您必须确保控制器可按要求使用,但我不推荐这种方法。这是一个例子来回答这个例子。在我看来,最好有自己的控制器,以隔离的方式调用东西,这样才是可重用的。我确实看到了这个答案:)但我希望类似于隔离作用域的情况。Thnx@JeanlucaScaljeri隔离镜也做了类似的事情:)它们只是把它藏起来,不让我们看到
.directive('helloWorld', function () {
return {
restrict: 'E',
scope: false,
template: '<button>Not isolated</button>',
link: function (scope, elem, attrs) {
elem.on("click", function(e) {
scope.$eval(attrs.callback, {$event: e});
});
}
}
});