在不同模块中的指令和控制器之间共享数据

Vin*_*ira 5 angularjs

我已经和AngularJS玩了几天,想出了一些我还无法解决的问题.

每个联系人都可以有多个地址和电话号码.由于插入和编辑联系人在UI级别需要几乎相同的功能,因此我决定创建一个类似以下的指令来处理地址和电话:

地址:

(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.
                ];

                // ...
            }
        }
})();
Run Code Online (Sandbox Code Playgroud)

电话:

(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.
                ];

                // ...
            }
        }
})();
Run Code Online (Sandbox Code Playgroud)

我省略了在指令中声明的方法来处理addressesphones变量.

这两个指令在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>
Run Code Online (Sandbox Code Playgroud)

这项工作完全符合我的预期,正确记录电话和地址.

现在,我想要做的是检索指令内的电话和地址,并将它们发送到服务器,以便记录在数据库的联系人.

我知道如何执行AJAX,但我不知道如何将指令和之间交换数据InsertController(与我想要的数据变量是:this.addressesaddressesEditor指令,并this.phonesphonesEditor指令).

我怎么能做到这一点?

Fed*_*kin 4

您可以使用共享服务/工厂来共享您想要共享的数据。

为了说明如何完成此操作,我创建了一些示例代码,使用服务在控制器和指令之间共享数据:

app.factory('SharedService', function() {
  return {
    sharedObject: {
      value: ''
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

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

希望有帮助