3

我有两个选项卡作为一个组件,其中包含一些输入字段,当我按下SAVE按钮时,我想获取它们的值并将其保存到服务器。问题是SAVE函数在index.js(父)中,输入字段TestComponent.js. 我找不到从组件中获取值并将其发送到父控制器(indexController.js)的方法。

我还尝试使用绑定,例如将所有数据保存为对象并将对象发送到,indexController.js但不幸的是我没有成功。

也请看一下PLUNKER的例子。

有人可以帮我吗。

索引.html

<body ng-app="heroApp">

<div ng-controller="MainCtrl as vm">

  <!-- Component Started -->
  <md-tabs>
    <tab-component> </tab-component>
  </md-tabs>
  <!-- Component Ended -->

  <button type="submit" ng-click="save()"> Save </button>

</div>

</body>

index.js

(function(angular) {
  'use strict';
angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
  var vm = this;

  this.onStatusChange = function(data) {
    vm.mandatoryFilesIncluded = data;
  };

  this.save = function() {
    vm.requestInProgress = true;
    vm.Upload.upload({
      url: someURL,
      arrayKey: '',
      data: {
        file: vm.files,
        name: vm.data.name,
        title: vm.data.title,
        description: vm.data.description,
      }
    }).then(function(response){
        alert("data is uploaded.");
    });
  };

});
})(window.angular);

tabComponent.html

<!-- Upload Tab-->
<md-tab id="picTab" label="Pic">
  <div layout-gt-xs="row" layout-align="start center">

    <md-input-container style="padding-left: 0">
      <md-button>
        <md-icon class="material-icons">attach_file</md-icon>
      </md-button>
    </md-input-container>

  </div>
</md-tab>


<!-- Info Tab-->
<md-tab id="infoTab" label="Info">
  <md-content class="md-margin">

    <div layout-gt-sm="row">
      <!-- Name -->
      <md-input-container>
        <label>Name</label>
        <input ng-model="vm.data.name" name="name" required>
      </md-input-container>

      <!-- Title -->
      <md-input-container class="md-block" flex-gt-sm>
        <label>Title</label>
        <input ng-model="vm.data.title" name="title" required>
      </md-input-container>
    </div>

    <!-- Description field -->
    <div layout="row">
      <md-input-container class="md-block" flex-gt-sm>
        <label>Description</label>
        <textarea ng-model="vm.data.description" name="descriptionField" rows="1"></textarea>
      </md-input-container>
    </div>
  </md-content>
</md-tab>

tabComponent.js

(function(angular) {
  'use strict';
angular.module('heroApp').component('tabComponent', {
  templateUrl: 'tabComponent.html',
  controller: myComponentController,
  controllerAs: 'vm',
  bindings: {
    statusChange: '&',
  }
});
})(window.angular);

function myComponentController() {
  var ctrl = this;
  ctrl.mandatoryFilesIncluded = false;
}
4

1 回答 1

3

由于save按钮在主控制器中触发,您可以在控制器中定义vm.data并将其绑定到组件:

bindings: {
  data: '=',
}

并将tab-component数据传递为:

 <tab-component data="vm.data"> </tab-component>

因此内部组件的任何更改vm.data也将反映在控制器中。

Working demo

于 2017-07-31T08:47:19.010 回答