Sharing data between directive and controller in different modules

I have been playing with AngularJS for only a few days and came up with something that I could not solve yet.

Each contact can have several addresses and phone numbers. Since inserting and editing a contact will require almost the same functionality at the user interface level, I decided to create a directive such as following addresses and phones:

Address:

(function () { var app = angular.module("AddressesEditorModule", []); app.directive("addressesEditor", function () { return { restrict: "E", templateUrl: "/addressesEditorTemplate.html", controller: function ($scope) { this.addresses = [ // this will hold addresses. ]; // ... } } })(); 

Telephone:

 (function () { var app = angular.module("PhonesEditorModule", []); app.directive("phonesEditor", function () { return { restrict: "E", templateUrl: "/phonesEditorTemplate.html", controller: function ($scope) { this.phones = [ // this will hold phones. ]; // ... } } })(); 

I skipped the methods declared inside the directives to work with the addresses and phones variables.

Both directives are also used in HTML:

 <div ng-app="ContactModule"> <div ng-controller="InsertController as insertCtrlr"> <!-- some other elements handling contact name goes here --> <addresses-editor></addresses-editor> <phones-editor></phones-editor> </div> </div> 

This work is exactly as I expected, with correctly recorded phones and addresses.

Now, what I want to do is get the phones and addresses inside the directive and send them to the server for writing to the contact in the database.

I know how to do AJAX, but I have no idea how to exchange data between directives and InsertController (variables with the data I want: this.addresses from the addressesEditor directive and this.phones from the phonesEditor directive).

How can i do this?

+5
source share
1 answer

You can use the shared / Factory service with the data you want to provide.

To illustrate how this can be done, I created some sample code using the service for exchanging data between controllers and directives:

 app.factory('SharedService', function() { return { sharedObject: { value: '' } }; }); 

http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=preview

Hope that helps

+4
source

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


All Articles