angularjs - Share data between a directive and a controller in different modules -
i have been playing angularjs few days , came not solve yet.
each contact can have multiple addresses , phone numbers. since inserting , editing contact require same functionality @ ui level, decided create directive following deal addresses , phones:
address:
(function () { var app = angular.module("addresseseditormodule", []); app.directive("addresseseditor", function () { return { restrict: "e", templateurl: "/addresseseditortemplate.html", controller: function ($scope) { this.addresses = [ // hold addresses. ]; // ... } } })();
phone:
(function () { var app = angular.module("phoneseditormodule", []); app.directive("phoneseditor", function () { return { restrict: "e", templateurl: "/phoneseditortemplate.html", controller: function ($scope) { this.phones = [ // hold phones. ]; // ... } } })();
i have omitted methods declared inside directives work addresses
, phones
variables.
both directives used @ html:
<div ng-app="contactmodule"> <div ng-controller="insertcontroller insertctrlr"> <!-- other elements handling contact name goes here --> <addresses-editor></addresses-editor> <phones-editor></phones-editor> </div> </div>
this work expected to, phones , addresses being correctly recorded.
now, want retrieve phones , addresses inside directive , send them server in order recorded @ contact @ database.
i know how perform ajax, have no idea how exchange data between directives , insertcontroller
(the variables data want are: this.addresses
addresseseditor
directive , this.phones
phoneseditor
directive).
how can accomplish this?
you can use shared service/factory data want share.
to illustrate how can done, created example code using service share data between controllers , directives:
app.factory('sharedservice', function() { return { sharedobject: { value: '' } }; });
http://plnkr.co/edit/q1vdkjp2tpvqqjl1lf6m?p=preview
hope helps
Comments
Post a Comment