Skip to content Skip to sidebar Skip to footer

Javascript Objects As Function Arguments In Angular Directive Properties

That title is a mouth-full! I've got some code written by another developer that's on leave and is unavailable to explain himself. None of us left in the office can figure out why

Solution 1:

"I thought the call to required was executed in the parent scope"

correct, the function is evaluated in the parent scope.

"so I don't understand how it's using variables that appear to be assigned a value in the template"

Not exactly, what happening is slightly different.

Let's examine the DDO.

return {
    restrict: 'E',
    scope: {
      required: '&isrequired'
    },
    templateUrl: 'path/to/template'
  }

and the function in the parent scope:

$scope.required = function(pathString, object){

}

the & symbol means passing a reference to a function that, as you mentioned, is evalueted in the parent scope, however the documentation explain that if the method requires some parameters, you must pass along with the function the name of these parameters:

<weird-directiveisrequired='required(fieldpath, item)'></weird-directive>

I understand that the syntax could be a little misleading, but here we're not invoking the function, we are specifying that fieldpath and item are keys that will be used later during the invocation phase.

Now inside your child scope, you can invoke the function passing as an argument a map, where each key represent a parameter name, and the correspondent value the value itself.

in your case:

<normal-directive
   isrequired='required({fieldpath:'Path.to.property', item: object})'></normal-directive>

last but not least, the evaluation of the function happens only after the evaluation of the parameters.

hope this helps.

Post a Comment for "Javascript Objects As Function Arguments In Angular Directive Properties"