我对如何将函数(委托(delegate))传递给 AngularJS 中的指令并在链接函数中使用它感到有点困惑。也许我完全不在乎,所以非常感谢您提供有关如何操作的任何指示。
我有以下 Controller
myApp.controller("QuestionCtrl", function($scope, $http) {
$scope.filter = function(query) {
console.log("filter filter", query);
};
$scope.replace = function(query, key) {
console.log('replace replace');
};
}
这是标记
<a class="Add Button" href="#" onsearch="filter(query)" onreplace="replace(hello, world)" showpane="#AddQuestionPane"><span>Ny fråga</span></a>
如您所见,我有 2 个属性指向我想在指令中使用的范围内的函数。
myApp.directive("searchreplace", function() {
return {
restrict: 'A',
scope: {
onsearch: "&",
onreplace: "&"
},
link: function(scope, element, attrs) {
element.bind("dblclick", function() {
scope.editMode = !scope.editMode;
if (scope.editMode) {
var replaceBox = angular.element('<input type="text" class="Search" placeholder="Ersätt" />');
replaceBox.keyup(function() {
//How do I call onsearch? Yes it is the wrong method, just a test
scope.onsearch({ query: replaceBox.val() });
});
element.after(replaceBox);
} else {
element.siblings(".Search").remove();
}
});
}
};
});
我这辈子都想不出如何调用作用域上的方法。我想在标记中指定它。这可能吗?
有没有更好的方案可以使用?
最佳答案
如您所见,我将 onsearch 和 onreplace 方法放在错误的元素上,当然它不会工作。我真傻!在我将属性移动到正确的元素(上面有 searchreplace 的元素)之后,一切正常。
关于javascript - 将函数传递给 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707829/