带有点的Angularjs范围变量在ng-repeat中显示为undefined

时间:2018-06-08 23:50:50

标签: angularjs

我试图提交一个angularjs表格。范围变量各自形成带有点的ng-model变量,例如ng-model="post.title", ng-model="post.pid".

我遇到的问题是,只要点击提交按钮, post.pid和post.title 就会一直警告值未定义

我已经为解决方案梳理了stackoverflow,我找到了这两个链接

AngularJS $scope form attribute is undefined after ng-submit

$scope with dot (.) not initializing values to input fields in angular

他们的回答是我必须首先初始化$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>

2 个答案:

答案 0 :(得分:0)

由于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);
}

答案 1 :(得分:0)

您的问题是post中的ng-repeat$scope.post不同,因为ng-repeat会创建一个子范围:

  

ngRepeat指令从a中为每个项目实例化一次模板   采集。每个模板实例都有自己的范围,给定的范围   loop变量设置为当前集合项

要让您的submitButton功能看到输入,您需要:

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

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

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