gpt4 book ai didi

javascript - ng-repeat 中的 ng-model 变得未定义

转载 作者:行者123 更新时间:2023-12-03 11:24:39 25 4
gpt4 key购买 nike

将 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"在您的输入标签上, Angular 不会将空值绑定(bind)到您的模型,因此当您从输入中删除值时,控制台会显示 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>

关于javascript - ng-repeat 中的 ng-model 变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26971930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com