将回调表单指令传递给AngularJS中的控制器函数
我有一个指令和一个控制器。指令在其隔离范围内定义函数。它还引用控制器中的函数。该函数接受回调。但是,当我从指令调用它并传入回调时,回调将作为未定义的方式传递。下面的代码将更清楚地说明这一点: 指示将回调表单指令传递给AngularJS中的控制器函数,angularjs,angularjs-directive,angularjs-controller,Angularjs,Angularjs Directive,Angularjs Controller,我有一个指令和一个控制器。指令在其隔离范围内定义函数。它还引用控制器中的函数。该函数接受回调。但是,当我从指令调用它并传入回调时,回调将作为未定义的方式传递。下面的代码将更清楚地说明这一点: 指示 directive('unflagBtn', ["$window", "api", function($window, api) { return { restrict: "E", template: "<a ng-clic
directive('unflagBtn', ["$window", "api",
function($window, api) {
return {
restrict: "E",
template: "<a ng-click='unflag(config.currentItemId)' class='btn btn-default'>Unflag</a>",
require: "^DataCtrl",
scope: {
config: "=",
next: "&"
},
controller: ["$scope",
function($scope) {
$scope.unflag = function(id) {
$scope.next(function() { //this callback does not get passed
api.unflag(id, function(result) {
//do something
return
});
});
};
}
]
};
}
]);
HTML
但这并不奏效。我不确定这是否重要,但我应该注意,该指令放在表单中,而表单则放在控制器中。为了说明结构:
<controller>
<form>
<directive>
<form>
<controller>
希望这是明确的,提前感谢 试试这个
controller: ["$scope",
function($scope) {
$scope.unflag = function(id) {
$scope.next({
cb: function() { //this callback does not get passed
api.unflag(id, function(result) {
//do something
return;
});
}
});
};
}
]
因此,在无法将对象传回控制器之后,我无意中发现了问题所在。发生了什么,我可能应该在问题中提到的是,如果我知道它的相关性是,这个指令unflagbtn的父范围实际上是我拥有的另一个指令的范围,称之为secondDirective。反过来,第二个指令从DataCtrl获取其作用域。简化的代码如下所示:
$scope.next({cb: function() { //this callback does not get passed still
api.unflag(id, function(result) {
//do something
return
});
}});
directive("secondDirective", [function(){
require: "^DataCtrl" // controller
scope: {
next: "&" // function that I was trying to call
}
...
// other code
...
}]);
directive("unflagbtn", [function(){
require: "^DataCtrl" // controller
scope: {
next: "&"
},
controller: ["$scope", function($scope){
$scope.unflag = function(){
$scope.next({cb: {cb: callBackFunctionIWantedToPass}); // this is what worked
}
}
}]);
因此,以这种方式传递回调解决了我返回控制器的问题。这很可能是因为我对angular的理解很差,所以我道歉,因为这很可能不是正确的方法,但它解决了我的问题,所以我想我会与大家分享
干杯,你想做什么。您正在尝试将常规控件传递给指令。当使用required时,您将获得的控制器(在本例中为父指令)。是指令之间通信的一种方式。你能解释一下你想做什么吗?下一个函数在控制器中,它控制着视图。它需要回调。我试图让不同的指令访问该函数。我这样做是因为我希望根据需要执行的操作,使用不同的指令向函数传递不同的回调。但由于某种原因,当我从指令调用next并向其传递回调时,当控制器接收到调用时,回调未定义。。。我希望这能让事情变得更清楚?嗨,很抱歉回复晚了。但这不起作用。。。当控制器接收到下一个cb的调用时,仍然未定义。
controller: ["$scope",
function($scope) {
$scope.unflag = function(id) {
$scope.next({
cb: function() { //this callback does not get passed
api.unflag(id, function(result) {
//do something
return;
});
}
});
};
}
]
directive("secondDirective", [function(){
require: "^DataCtrl" // controller
scope: {
next: "&" // function that I was trying to call
}
...
// other code
...
}]);
directive("unflagbtn", [function(){
require: "^DataCtrl" // controller
scope: {
next: "&"
},
controller: ["$scope", function($scope){
$scope.unflag = function(){
$scope.next({cb: {cb: callBackFunctionIWantedToPass}); // this is what worked
}
}
}]);