javascript - Angular Custom Directives: Calling a function with arguments from within the link function -
i'm building list of clickable options filtered input, using 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) { // 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 want call selectfn properties option called it. like:
option-select=“selectfn(option.value)”
or
scope.optionselect(option);
is possible? can call function in scope , pass arguments within link function?
for customization reasons, cannot use combo box library, ui-select.
you passing result of function, evaluated in parent scope, instead of function itself. can evaluate expression , execute resulting function.
so, should try this
<combobox input-model="mymodel" options="mylist" option-label="label" option-select="selectfn">
in markup, , in directive
link: function(scope, elem, attrs) { scope.optionselected = function(option) { // stuff here... scope.optionselect()(option); } }
notice expression in option-select="selectfn"
handed isolate scope wrapped in optionselect
function. when evaluate it, function want. that's why use scope.optionselect()(option)
see directive working here: http://plnkr.co/edit/zgymbisygnt4ijffvj6g
from https://docs.angularjs.org/api/ng/service/$compile
& or &attr - provides way execute expression in context of parent scope. if no attr name specified attribute name assumed same local name. given , widget definition of scope: { localfn:'&myattr' }, isolate scope property localfn point function wrapper count = count + value expression. it's desirable pass data isolated scope via expression parent scope, can done passing map of local variable names , values expression wrapper fn. example, if expression increment(amount) can specify amount value calling localfn localfn({amount: 22})
Comments
Post a Comment