4

How to get some data from controller and use it inside directive thats not a problem. But I stack with such situation when I need get data from directive and use it in my controller.

For exmpl:

My controller:

function MyController($scope, $location, myDirective) {
    "use strict";

    // here i need use scope.importantValue and create() method from directive

}

My directive:

        .directive("myDirective", function() {
"use strict";
return {
    restrict: 'A',
    template: '<div></div>',
    replace: true,
    scope: {
        data: '=',
    },
    link: function(scope, elm) {
        scope.importantValue = "value";

        function create() {
            console.log("Directive works...");
        }

};
})

How I can use variables or/and methods from directive inside my controller?

3
  • 1
    Why would you want to do that? Commented May 10, 2013 at 13:38
  • 2
    you are not suppose to do it Commented May 10, 2013 at 13:56
  • We moved to directive some part of code that similar for few views and this directive contains some variables that can be used in other parts of project. I wanna know is it posible to use this variables in a controller or not? Commented May 10, 2013 at 14:03

1 Answer 1

9

The simplest way to accomplish this is to make both your controller and directive get importantValue and create() from a service.

angular.module(/* Your module */).service('sharedData', function () {
    return {
        importantValue: "value",
        create: function () {
            console.log("Directive works...");
        }
    };
});

Now you can inject sharedData into your directive and controller and access importantValue and create() from either place.

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

1 Comment

Good! That what I really need!+

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.