0

JQuery to Directive

I want to call a method from the scope of this directive but can't seem to work it out (if possible).

$("my-directive").first().scope().loadData();

Directive Looks Something Like This

I would like to call the loadData function from the directive code below.

app.directive("myDirective", function () {
    return {
        restrict: "E",
        templateUrl: "..."
        scope: {},
        controller: function ($scope, $element, $attrs) {
            var self = this;
            $scope.loadData = function () {
               ... 
            };
        }
    };
});

2 Answers 2

1

Scope is accessible inside the directive

You can get any child of the element of which directive is applied and get scope of it.

$('my-directive').first().children(":first").scope().loadData()
Sign up to request clarification or add additional context in comments.

Comments

0

Strajk's answer is correct!

When Code is Added Dynamically setTimeout Needed

In the following example detail row has a nested directive (random-testees). I get the scope from that to dynamically compile the directive (dynamic and late-bound). The setTimeout is needed because it seems to take a bit before the

var detailRow = e.detailRow;

// Compile the directive for dyanmic content. 
angular.element(document).injector().invoke(function ($compile) {
    var scope = angular.element(detailRow).scope();
    $compile(detailRow)(scope);
});

// Get some data from directive. 
var testId = detailRow.find("random-testees").attr("testid");

// Wait, and call method on the directive. 
setTimeout(function () {
    var randomTesteesScope = $("random-testees").first().children(":first").scope();
    randomTesteesScope.loadTestees(this);
}.bind(testId),200);

Not Very Confident About This

This seems a little brittle since I was getting mixed results with a 100 ms timeout sometimes and error when the randomTesteesScope returned undefined.

2 Comments

Yeah, I think my code above is good only for inspecting webapp from console... I wouldn't use it in app's source code.
@Strajk, but I don't have a choice here. I need to dynamically load the directive content. And then call a method on it.

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.