Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.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 - Fatal编程技术网

Javascript 具有原始绑定的指令中的函数回调

Javascript 具有原始绑定的指令中的函数回调,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,将要在init上调用的函数传递给指令,该函数由字符串属性表示,然后解析并使用该属性。问题在于,使用时,函数绑定不再附加/绑定到函数所属的对象。这就是我的意思() var app=angular.module('plunker',[]); 应用程序控制器('MainCtrl',函数($scope){ $scope.name='World'; $scope.container={ x:null ,设置:功能(x){ console.log(this);//这里应该是$scope.container

将要在init上调用的函数传递给指令,该函数由字符串属性表示,然后解析并使用该属性。问题在于,使用时,函数绑定不再附加/绑定到函数所属的对象。这就是我的意思()


var app=angular.module('plunker',[]);
应用程序控制器('MainCtrl',函数($scope){
$scope.name='World';
$scope.container={
x:null
,设置:功能(x){
console.log(this);//这里应该是$scope.container,但它的窗口
这个.x=x;
}
};
});
app.directive('dir',['$parse',function($parse){
返回{
限制:“E”
,transclude:false
,范围:true
,链接:函数(范围、元素、属性){
var callback=attrs.setup
,someCalcVar=10
;
$parse(回调)(范围)(someCalcVar);
}
};
}]);
container.x=='{{container.x}}'

有没有办法实现我想要的?也许有更好的方法来设计它,但仍然为回调和相关变量保留某种容器

编辑:


一个简单的胜利可能是检查回调是否有
,然后使用
func.bind(substr(callback,…)
手动绑定它。。。有没有什么内置的东西可以做到这一点?或者,是否有一种更干净的方法来解决所有这些问题?

这不是最优雅的解决方案,但您始终可以创建一个函数来结束对容器的调用:

$scope.callableSetup = function(x) {
    $scope.container.setup(x);  
}
我正在发布,使用下划线JS绑定,我可以在控制器中强制实现这一点

$scope.container.setup = _.bind($scope.container.setup, $scope.container);
仍然不是我想要的优雅,仍然在等待穿着闪亮盔甲的骑士的回答

编辑:进行一次

尝试:

var that = this;
$scope.container = {
    x: null,
    setup: function(x) {
        console.log(that); //this here should be $scope.container, but its window
        console.log(x);
        that.x = x;
    }
};

另一种可能的解决办法:

var self;
$scope.container = self = {
    x: null, 
    setup: function(x) {
        console.log(this);
        self.x = x;
    }
};

这确实有效,但正如你所说,这不是最优雅的。仍然坚持要一些非常好的东西:)也许像这样的东西@AlexandrinRus这方面的问题是指令必须了解
容器
,这不是它通常需要了解/实施的内容。为了轻松取胜,请使用ng init。只需说ng init=“container.setup()”就不应该
that=$scope.container
而不是
this
?这是控制器,它是一个参考
var self;
$scope.container = self = {
    x: null, 
    setup: function(x) {
        console.log(this);
        self.x = x;
    }
};