Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS communication between controller and directive

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?

like image 677
Lugaru Avatar asked Jan 14 '23 10:01

Lugaru


1 Answers

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.

like image 108
Noah Freitas Avatar answered Jan 22 '23 21:01

Noah Freitas