Angularjs 范围变量,点在 ng-repeat 中显示未定义



我有一个angularjs表单正在尝试提交。范围变量具有每个形式的ng-model变量,例如点ng-model="post.title", ng-model="post.pid".

我遇到的问题是,每当单击提交按钮时,post.pid 和 post.title都会不断提醒未定义的值。

我已经梳理了堆栈溢出的解决方案,我找到了这两个链接

AngularJS$scope表单属性在ng提交后未定义

$scope点 (.( 时不初始化角度输入字段的值

他们的回答是我必须首先初始化$scope.post所以我根据两个链接提供的解决方案实现如下。

$scope.post = {}; 
$scope.submitButton = function(){
alert($scope.post.pid);
alert($scope.post.title);
}

然而,每次单击提交按钮时,它都会不断提醒未定义

以下是整个代码

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="post in posts">
<form>
post Id<br>
<input type='text' ng-model="post.pid" >
<br> post Title<br>
<input type='text' ng-model="post.title" name="title">
<br>
<input type='button' id='but_save' value='Save' ng-click="submitButton()">
</form>
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http, $parse) {
$scope.posts = [
{
"pid" : "1",
"title" : "title1"
},
{
"pid" : "2",
"title" : "title2"
},
{
"pid" : "3",
"title" : "title3"
},
]


$scope.post = {}; 

$scope.submitButton = function(){
alert($scope.post.pid);
alert($scope.post.title);
}
});
</script>
</body>
</html>

由于ng-repeat为每个项目创建一个子作用域,因此它对父作用域不可见。

post对象作为参数传递给提交函数:

<div ng-repeat="post in posts">
<form>
post Id<br>
<input type='text' ng-model="post.pid" >
<br> post Title<br>
<input type='text' ng-model="post.title" name="title">
<br>
<input type='button' id='but_save{{$index}}' value='Save'
̶n̶g̶-̶c̶l̶i̶c̶k̶=̶"̶s̶u̶b̶m̶i̶t̶B̶u̶t̶t̶o̶n̶(̶)̶"̶
ng-click="submitButton(post)" />
</form>
</div>

在函数中使用该参数:

$scope.submitButton = function(post){
̶a̶l̶e̶r̶t̶(̶$̶s̶c̶o̶p̶e̶.̶p̶o̶s̶t̶.̶p̶i̶d̶)̶;̶
alert(post.pid);
̶a̶l̶e̶r̶t̶(̶$̶s̶c̶o̶p̶e̶.̶p̶o̶s̶t̶.̶t̶i̶t̶l̶e̶)̶;̶
alert(post.title);
}

你的问题是ng-repeat中的post$scope.post不同,因为ng-repeat创建了一个子作用域:

ngRepeat 指令从 收集。每个模板实例都有自己的范围,其中给定的 循环变量设置为当前集合项

要让submitButton函数查看输入,您需要:

  • 要么传递它提交的帖子的$index并从$scope.posts获取值
  • 或直接将值作为函数的参数传递

我宁愿避免索引操作并选择第二个选项:

<input type='button' id='but_save' value='Save' ng-click="submitButton(post.pid,post.title)">

最新更新