AngularJS communication between controller and directive

How to get some data from the controller and use it inside the directive is not a problem. But I am confronted with a situation where I need to get data from a 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 can I use the variables or methods from the directive inside my controller?

+4
source share
1 answer

The easiest way to do this is to make both your controller and the directive get importantValue and create() from the service.

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

Now you can enter sharedData in your directive and controller and access importantValue and create() from anywhere.

+9
source

Source: https://habr.com/ru/post/1480113/


All Articles