我对angular是个新手,并且坚持使用动态数据绑定。我有4个数据字段,2个是静态的,2个是在添加按钮后动态添加的。当我单击add按钮时,显示屏上只显示两个字段,其余数据不会填充。我可能在数据传递过程中犯了一些错误。前两个字段是静态的,后两个字段是动态的,需要在用户单击时添加。使用form时也会发生同样的情况。有谁能帮我解决这个问题吗。提前谢谢。下面是我的代码:
控制器:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.items = [];
  $scope.itemsToAdd = [{
    firstName: '',
    lastName: ''
  }];
  $scope.add = function(itemToAdd) {
    var index = $scope.itemsToAdd.indexOf(itemToAdd);
    $scope.itemsToAdd.splice(index, 1);
    $scope.items.push(angular.copy(itemToAdd))
  }
  $scope.addNew = function() {
    $scope.itemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});视图(HTML):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>
  <div ng-repeat="item in items">
     {{item.regno}} {{item.section}}
    {{item.firstName}} {{item.lastName}}
  </div>
    <input type="text" ng-model="itemToAdd.regno" />
    <input type="text" ng-model="itemToAdd.section" />
  <div ng-repeat="itemToAdd in itemsToAdd">
    <input type="text" ng-model="itemToAdd.firstName" />
    <input type="text" ng-model="itemToAdd.lastName" />
    <button ng-click="add(itemToAdd)">Add</button>
  </div>
  <div>
    <button ng-click="addNew()">Add new</button>
  </div>
</body>发布于 2017-03-30 18:41:00
您可以在添加后尝试:
$scope.$apply();发布于 2017-03-30 18:57:30
本节内容:
 <input type="text" ng-model="itemToAdd.regno" />
 <input type="text" ng-model="itemToAdd.section" />在ng-repeat之外,因此不知道itemToAdd是什么;将其更改为:
<div ng-repeat="itemToAdd in itemsToAdd">
 <input type="text" ng-model="itemToAdd.regno" />
 <input type="text" ng-model="itemToAdd.section" />
 <input type="text" ng-model="itemToAdd.firstName" />
 <input type="text" ng-model="itemToAdd.lastName" />
<button ng-click="add(itemToAdd)">Add</button>
但是这只会给你一个空的显示,因为你没有在任何地方定义regno和section的默认值。在你的代码中定义它们:
$scope.itemsToAdd = [{
  firstName: '',
   lastName: '',
  section: 'defaultSection',
  regno: 'defaultRegNo'
}];和
 $scope.addNew = function() {
$scope.itemsToAdd.push({
  firstName: '',
   lastName: '',
  section: 'defaultSection',
  regno: 'defaultRegNo'
});
};发布于 2017-03-31 13:47:14
来自directives-that-create-scopes angular文档
重复一些指令,如ng-
和ng-,创建新的子作用域并将该子作用域附加到相应的DOM元素
在你的情况下,
itemToAdd.regno & itemToAdd.section are different modals and in different scope 请比较itemToAdd.firstName & itemToAdd.lastName。
因此,regno & section不是ng- itemToAdd内部重复的一部分。
这就是为什么你不能进入你的$scope.items
您必须在add函数中添加regno & section
$scope.add = function(itemToAdd) {
    itemToAdd.regno = $scope.itemsToAdd.regno;
    itemToAdd.section = $scope.itemsToAdd.section;
    $scope.items.push(angular.copy(itemToAdd))
    console.log($scope.items);
  }https://stackoverflow.com/questions/43115417
复制相似问题