ng-repeat中的ng模型变得未定义

ng-model in ng-repeat become undefined

本文关键字:未定义 模型 中的 ng ng-repeat      更新时间:2023-09-26

使用Javascript和angularJs,我输入以下代码:

.JS

 $scope.myObj = {
     'sthg': '',
     'a': [{
          'b' : ''
     }]
 }

.HTML

<p ng-repeat="radio in fiche.radios">
    <input type="text" ng-model="radio.code" placeholder="Numéro de cliché" ng-required="true" />
    <span >
      <button type="button"ng-click="removeRadioList($index);" ng-disabled="fiche.radios.length === 1">
        <i>X</i>
      </button>
    </span>
  </p>

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

在我的应用程序中,$scope.myObj.a[0].b未定义 ng-repeat(如果我删除 ng-repeat,它将被定义)。在 plunkr 中,即使在运行 ng-repeat 之后,它也被定义,但是当我在输入中输入某些内容然后删除它时,我设法有了这种行为。

我不明白发生了什么,我想了解为什么以及这是否是一个好方法?

因为您在输入标签上设置了ng-required="true",因此当您从输入中删除值时,角度不会将空值绑定到您的模型,当您从控制台中删除值时,您的控制台显示您radios.code为未定义。

请参阅下面的工作演示:

(function() {
  "use strict";
  var app = angular.module('plunker', []);
 
  app.controller('MainCtrl', function($scope, $log) {
    $scope.ficheInit = {
      'user_id': '',
      'radios': [{
        'code': ''
      }]
    };
    $log.log($scope.ficheInit);
    $scope.fiche = angular.copy($scope.ficheInit);
    $log.log($scope.fiche);
    $scope.addRadioList = function() {
      $scope.fiche.radios.push({
        'code': ''
      });
    }
    $scope.removeRadioList = function(i) {
      $scope.fiche.radios.splice(i, 1);
    }
    $scope.disableAddRadio = function() {
      console.log($scope.fiche.radios);
      return !(angular.isDefined($scope.fiche.radios[$scope.fiche.radios.length - 1].code) || $scope.fiche.radios.length < 1);
    }
  });
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker">
  <div ng-controller="MainCtrl">
    <button ng-click="showForm=true;">SHOW</button>
    <div ng-show="showForm">
      <button ng-click="addRadioList();" ng-disabled="disableAddRadio()">Ajouter un cliché</button>
      <p ng-repeat="radio in fiche.radios">
        <input type="text" ng-model="radio.code" placeholder="Numéro de cliché" />
        <span>
          <button type="button" ng-click="removeRadioList($index);" ng-disabled="fiche.radios.length === 1">
            <i>X</i>
          </button>
        </span>
      </p>
    </div>
    {{fiche.radios}}
  </div>
</div>