Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share data between a directive and a controller in different modules

Tags:

angularjs

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

Each contact can have multiple addresses and phone numbers. Since inserting and editing a contact will require almost the same functionality at the UI level, I decided to create a directive like to following to deal with 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.
                ];

                // ...
            }
        }
})();

Phone:

(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 have omitted the methods declared inside the directives to work with the addresses and phones variables.

Both directives are used like this at the 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 exactly as I expected to, with phones and addresses being correctly recorded.

Now, what I want to do is to retrieve the phones and addresses inside the directive and send them to the server in order to be recorded at the contact at the database.

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

How can I accomplish this?

like image 374
Vinícius Gobbo A. de Oliveira Avatar asked Oct 01 '22 01:10

Vinícius Gobbo A. de Oliveira


1 Answers

You can use a shared Service/Factory with the data you want to share.

To illustrate how it can be done, I created some example code using a service to share data between Controllers and Directives:

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

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

Hope that helps

like image 144
Fedaykin Avatar answered Nov 15 '22 09:11

Fedaykin