I'm building a list of clickable options that is filtered by an input, using a custom directive.
HTML:
<combobox
input-model="myModel"
options="myList"
option-label="label"
option-select="selectFn()"></combobox>
The Directive (simplified):
app.directive("combobox", function() {
return {
restrict: "E",
replace: true,
template: "<input type=‘text’ ng-model=‘inputModel’ />" +
"<button ng-repeat='option in options | " +
"filter: inputModel’" +
"ng-mousedown=‘optionSelected(option)’" +
">{{option[optionLabel]}}</button>",
scope: {
inputModel: "=",
options: "=",
optionLabel: "@",
optionSelect: "&"
},
link: function(scope, elem, attrs) {
scope.optionSelected = function(option) {
// some stuff here...
scope.optionSelect();
}
}
}
})
Scope:
$scope.myList = [
{ label: "First Option", value: 1 },
{ label: "Second Option", value: 2 },
{ label: "Second Option", value: 2 }
]
$scope.selectFn() = function() {
// doing stuff here...
}
But I want to call selectFn with properties from the option that called it. Something like:
option-select=“selectFn(option.value)”
or
scope.optionSelect(option);
Is this possible? Can I call a function in scope and pass arguments from within the link function?
For customization reasons, I cannot use a combo box library, like ui-select.
You are passing the result of the function, evaluated in the parent scope, instead of the function itself. You can evaluate your expression and then execute the resulting function.
So, what you should try is this
<combobox
input-model="myModel"
options="myList"
option-label="label"
option-select="selectFn">
in your markup, and then in your directive
link: function(scope, elem, attrs) {
scope.optionSelected = function(option) {
// some stuff here...
scope.optionSelect()(option);
}
}
Notice that the expression in option-select="selectFn" will be handed to your isolate scope wrapped in the optionSelect function. When you evaluate it, you get the function you want. That's why you use scope.optionSelect()(option)
See your directive working here: http://plnkr.co/edit/zGymbiSYgnt4IJFfvJ6G
From https://docs.angularjs.org/api/ng/service/$compile
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With