2

I have to access variable defined in directive and access it in the controller using angularjs directive :

app.directive('htmlData', function ($compile) {

    return {
        link: function($scope, element, attrs) {
                $(element).on('click', function() {
                    $scope.html = $compile(element)($scope).html();
                });

                return $scope.html;
        }

    };
});

and use $scope.html in controller.

2 Answers 2

1

Since you are not creating an isolate scope (or a new scope) in your directive, the directive and the controller associated with the HTML where the directive is used are both using/sharing the same scope. $scope in the linking function and the $scope injected into the controller are the same. If you add a property to the scope in your linking function, the controller will be able to see it, and vice versa.

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

Comments

0

As you set the variable in the $scope, all you got to do is to bind to it normally. In your case, osmehting like:

<div html-data>{{html}}</div>

Maybe you're not seeing the update because it lacks a $scope.$apply().

Anyway, let me say that I see two problems on you code. First of, you could use ng-click directive to attach click events to your HTML.

Secondly, why would you recompile your HTML every time? There is almost no need for that. You may have a big problem, because after first compilation, your template is going to be lost, so recompiling will render it useless.

If you need to get the element, you can inject $element.

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.