Angularjs返回错误无法设置属性' subcomment_like'在ng-repeat中未定义的

时间:2018-06-10 11:18:03

标签: angularjs

我试图在ng-repeat中使用angularjs发布和显示/更新内容。

我能够获得

中显示的标题值
<div ng-repeat='post in posts'>
  {{ post.title }}
</div>

现在我试图在第一个ng-repeat()函数中获取子数据,如下面的情况,但它返回错误无法设置属性&#39; subcomment_like&#39;在ng-repeat中未定义

<div ng-repeat='post in posts'>

  {{ post.title }}
  <div ng-repeat='comment in post.comment'>

    {{comment.subcomment_like}}</div>
</div>

我也试过

$scope.post.comment[index].subcomment_like = response.data[0].subcomment_like;
$scope.comment[index].subcomment_like = response.data[0].subcomment_like;

但没有运气。在控制台中,所有值都能很好地显示出来。

下面是代码

<script>
  var fetch = angular.module('myapp', []);
  fetch.controller('fetchCtrl', ['$scope', '$http', function($scope, $http) {

        //initialize an arrays of commenting
        $scope.commenting = [];
        $scope.posts = [];

        $scope.setResponse = function(index, title, subcomment_like) {

          $http({
            method: 'post',
            url: 'content.php',
            data: {
              subcomment_like: subcomment_like,
              title: title
            }
          }).then(function successCallback(response) {

            $scope.posts[index].title = response.data[0].title;

            // Update total likes subcomment values on the post
            $scope.post.comment[index].subcomment_like = response.data[0].subcomment_like;


            $scope.commenting.push(response.data[0]);

          });
        }


      ]);
</script>


<div ng-repeat='post in posts'>

  {{ post.title }}

  <div ng-repeat='comment in post.comment'>

    {{comment.subcomment_like}}</div>
</div>
为了清晰起见,

//更新了部分

在您的代码中,{{comment.subcomment_like}}在角度视图中显示json的 1 值。现在发布了

data: {
              subcomment_like: 2
            }

我想要的是发布subcomment_like: 2来替换json中显示的 subcomment_like 的现有 1 值。

现在,我可以在发布后的{/ 1>视图/页面中显示{{comment.subcomment_like}} 2 的值

1 个答案:

答案 0 :(得分:0)

您的JSON无效,但是如果您拥有正确的JSON,它应该如下工作,

  

$ scope.posts = [{       “id”:“1”,       “标题”:“我的第一个头衔。”,       “评论”:[         {           “id”:“359”,           “subcomment_like”:“1”         }       ]}];

<强>样本

var app = angular.module('test',[]);
app.controller('testCtrl',function($scope){
$scope.posts = [
  {
    "id": "1",
    "title": "my first title.",
    "comment": [
      {
        "id": "359",
        "subcomment_like": "1"
      }
    ]
  }
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="test" ng-controller="testCtrl">
<div ng-repeat='post in posts'>
  {{ post.title }}
  <div ng-repeat='comment in post.comment'>
  {{comment.subcomment_like}}
  </div>
</div>
</body>

修改

只需将JSON更新为follwos,

$scope.posts.[0].comment[0].subcomment_like = 2;