1

I have an AngularJS directive with function parameter, and it works perfectly when I call the directive simply it works, and I want to generalize it. What I got so far:

.directive('panelBox', function () {
    return {
        restrict: 'E',
        scope: {
            values: '=',
            calculatefn: '&'
        },
        templateUrl: '/ProfitCalculator/PanelBox',
        controller: function ($scope) {


            $scope.calculate=function() {
                $scope.calculatefn();
            }
        }
    }
})

in the main scope:

$scope.smartBookValues= {
name:'Smart Book',
text:'Smart book header',
controls:[]
};

and the html:

<panel-box values="smartBookValues" calculateFn="smartBookCalculateFn()"></panel-box>

now I'm trying to bind the values and calculateFn, so I started with calculateFn and did:

$scope.smartBookValues= {
name:'Smart Book',
text:'Smart book header',
controls:[],
calculateFn:'smartBookCalculateFn()'
};

and the html:

<panel-box values="smartBookValues" calculateFn="{{smartBookValues.calculateFn}}"></panel-box>

but i get: [$parse:syntax]

Syntax Error: Token '{' invalid key at column 2 of the expression [{{smartBookValues.calculateFn}}] starting at [{smartBookValues.calculateFn}}].

Somaye
  • 114
  • 1
  • 3
  • 11
  • You're passing the function as a String, have you tried passing an actual function? – GMaiolo Jan 03 '18 at 13:58
  • how do I do that? – Erez Konforti Jan 03 '18 at 14:36
  • Declare ```calculateFn: function() { console.log('something') }```, remove the braces in the HTML and pass the attribute with a hyphen like this: ```calculate-fn="smartBookCalculateFn()"```. Also you declared the scope in the directive as ```calculatefn``` with a lower case ```f```, be careful with that. – GMaiolo Jan 03 '18 at 14:45
  • not working at all now,doesn't get to the function. Also its still not binding to a dynamic function name stored in my scope... – Erez Konforti Jan 03 '18 at 15:02

1 Answers1

0

First, you declare as:

calculatefn: '&'   <-- small 'f'

so syntax in html is like:

<panel-box values="smartBookValues" calculatefn="smartBookValues.calculateFn"></panel-box>  <-- no need for {{}}, as you passing as reference to scope, not as text

search Google for "how to pass function in to angular directive"

Dmitri Algazin
  • 3,332
  • 27
  • 30