Reputation: 2052
im a bit stumpled with how you can pass a function (delegate) to a directive in AngularJS and use it in the link-function. Maybe I am totally off so any pointers on how you would do it is greatly appreciated.
I have the following 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');
};
}
This is the markup
<a class="Add Button" href="#" onsearch="filter(query)" onreplace="replace(hello, world)" showpane="#AddQuestionPane"><span>Ny fråga</span></a>
As you can see I've got 2 attributes that points to functions on my scope that I would like to use in my directive.
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();
}
});
}
};
});
I cant for the life of me figure out how to call the method on the scope. I want to specify it in the markup. Is that possible?
Is there a better solution to use?
Upvotes: 3
Views: 4591
Reputation: 2052
As you can see I put the onsearch and onreplace methods on the wrong element, of course it dont work then. Stupid of me! After I moved the attributes to right element (the one with searchreplace on it) everything works.
Upvotes: 3