简体   繁体   中英

Sharing data of a ng-repeat form field across controllers

I'm making an order form for a business card with a button to add another business card. I want the button to create another business card form and all the data from the forms to be shared with the controller of another view.

I have two templates connected to their respective controllers.

  • order.html, order.js
  • confirm.html, confirm.js

Code Samples:

order.js

.factory('Cards', function () {
var Cards = []

return Cards
})
.controller('TestCtrl', function ($scope, Cards) {
  $scope.person0={name: '', email:'', description:''}
  $scope.person1={name: '', email:'', description:''}
  if (Cards.length < 2) {
    Cards.push($scope.person0);
    Cards.push($scope.person1);
  }
 }

order.html

<md-toolbar layout='column' layout-align='center' ng-repeat="card in Cards">
        <md-button layout-margin layout-padding flex='100' class='md-raised md-primary'>
          <h1>{{ card.name }}</h1>
          <h1>{{ card.email }}</h1>
          <h1>{{ card.description }}</h1>
        </md-button>
        <div layout='column' layout-align='center center' >
          <input type="text" style="color:black;" flex='' ng-model="card.name">
          <input type="text" style="color:black;" flex='' ng-model="card.email">
          <input type="text" style="color:black;" flex='' ng-model="card.description">
        </div>
 </md-toolbar>

about.js

.controller('AboutCtrl', function ($scope, Cards) {
    $scope.person0=Cards[0];
    $scope.person1=Cards[1];
  });

about.html

<div ng-repeat="card in Cards">
    <md-toolbar layout='column' layout-align='center'>
      <md-button layout-margin layout-padding flex='100' class='md-raised md-primary'>
        <h1>{{card.name}}</h1>
        <h1>{{card.email}}</h1>
        <h1>{{card.description}}</h1>
      </md-button>
    </md-toolbar>
    <md-content>

    </md-content>
  </div>

I want the form data from order.html to be displayed on confirm.html

The Cards collection gets logged for both views but the ng-repeat templates do not get displayed.

Slow down and take a closer look.

In about.html it looks like you want to loop through cards.

<div ng-repeat="card in Cards">

But in about.js each individual card is assigned to scope.

$scope.person0=Cards[0];  // no reference in template

To fix this, put the Cards on the about.js scope.

$scope.Cards = Cards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM