通过从不同的控制器$scopes将索引推送到不同的变量中

Push index into different variables by $scopes from different controller

本文关键字:索引 变量 控制器 scopes      更新时间:2023-09-26

>我在从表单推送输入时遇到问题

下面有一些代码行检测到错误我也在CodePen上重新创建了它

$scope.dish.comments.push(Object.keys{rating: $scope.comment.rating, comment: $scope.comment.comment, author: $scope.comment.author, date: $scope.comment.date});

因此,每次提交表单时,我总是在控制台中收到这样的通知

类型错误: 无法读取未定义的属性"注释"

我已经在另一个控制器中声明了$scope.dish = dish;,所以我希望我可以从另一个控制器访问它,但它没有像我希望的那样工作

您正在尝试在两个控制器之间共享数据,我建议对 DishDetails 使用服务工厂,然后在两个控制器上注入依赖项,然后修改后的数据将反映到每个控制器。

下面介绍如何使用工厂服务共享数据。

function factory() {
  var service = {
    set: setData,
    get: getData
  };
  service.records = [{
    FirstName: 'FirstName',
    LastName: 'LastName',
    Age: '21'
  }];
  return service;
  function getData() {
    return service.records;
  }
  function setData(data) {
    service.records.push(data);
  }
}
angular
  .module('mainApp', [])
.factory('dataRecords', factory)
.controller('AddDataController', function($scope, dataRecords) {
  $scope.AddRecord = function() {
    var data = {
      FirstName: $scope.FirstName,
      LastName: $scope.LastName,
      Age: $scope.Age
    }
    dataRecords.set(data)
  }
})
.controller('ViewDataController', function($scope, dataRecords) {
  $scope.records = dataRecords.get();
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link data-require="bootstrap-css" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<div ng-app="mainApp">
  <div ng-controller="AddDataController">
    First Name:
    <input type="text" ng-model="FirstName" name="FirstName" placeholder="Enter First Name" required>Last Name:
    <input type="text" ng-model="LastName" placeholder="Enter Last Name">Age:
    <input type="number" ng-model="Age">
    <button type="button" ng-click="AddRecord()">ADD</botton>
  </div>
  <div ng-controller="ViewDataController" class="container">
    <h3>Record List Controller</h3>
    <table class="table">
      <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Age</th>
      </tr>
      <tr ng-repeat="person in records">
        <td>{{ person.FirstName }}</td>
        <td>{{ person.LastName }}</td>
        <td>{{ person.Age }}</td>
      </tr>
    </table>
  </div>
</div>

将 ng-controller="DishDetailController" 添加到父行内容div 中,以便其他控制器将继承 $scope.dish。因此:

<div class="row row-content" ng-controller="DishDetailController">
      <div class="col-xs-9 col-xs-offset-1" >
      ...
      </div>
      <div class="col-xs-9 col-xs-offset-1" ng-controller="DishCommentController">
      ...
      </div>
</div>