0

I want to create a custom directive (let's call it MyDragSource) that can obtain its "drag context" by calling a function on the scope, like so:

<div my-drag-source drag-context="getDragContext">

In this case, getDragContext is a function that's defined on the scope:

$scope.getDragContext = function() { // return drag source }

I want getDragContext to be lazily invoked when the drag operation begins, not evaluated up front. How can I do this?

In my custom directive, I've tried the following:

$scope.$eval($attrs.dragContext);

However, that doesn't yield the desired result.

2
  • it's not going to be invoked until you actually execute it with () Commented Feb 17, 2015 at 1:18
  • can you show the code of the directive? right now you are assigning a property to a function, not the result of the function, but you appear to be trying to evaluate the variable inside the directive like it's outside on the scope.... Commented Feb 17, 2015 at 1:20

2 Answers 2

2

Pass the function as an attribute on your directive:

<div my-drag-source drag-context="getDragContext()" >

Use isolate scope in your directive, and import dragContext using &, which defines the scope property as a function that returns the results of evaluating the attribute's contents in the parent scope (in this case, $scope.$parent.$eval(attrs.dragContext)):

scope: {
  dragContext: '&'
}

Then you can call the function whenever you want in link function:

$scope.dragContext()

If you pass the method without parentheses, you can still call it from the link function, you just need to invoke the function, by adding another set of parens:

$scope.dragContext()()

Sign up to request clarification or add additional context in comments.

4 Comments

Excellent, thanks so much! Just one minor correction: on the scope definition above, you need "dragContext:" rather than "drag-context:"
@Wolf Just be sure that you understand what the scope isolation does in this solution.
Just for correctness, & does not indicate a reference to an external function. It is just shorthand for adding a function dragContext to the directive scope that returns $scope.$parent.$eval(atts.dragContext). The expression attrs.dragContext can be any valid angular expression, not just a method invocation or method.
@JoeEnzminger thank you for providing this additional information, I will update
0

You can call it like this :

var data = $scope[$attrs.dragContext]();

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.