Angularjs发表评论

时间:2016-03-16 16:17:20

标签: javascript arrays angularjs

我的工厂

var obj = {
    posts: [
    {
        "text":"text",
        "date":null,
        "like":0,
        "comments":[
            {"comment":"Yorum 1", "like":100},
            {"comment":"Yorum 2", "like":200},
            {"comment":"Yorum 3", "like":300}
        ]
    },
    {
        "text":"text2",
        "date":null,
        "like":0,
        "comments":[
            {"comment":"Yorum 4", "like":500},
            {"comment":"Yorum 5", "like":600}
        ]
    }
        ]
};
return obj;

PostCommand

$scope.posts = PostFactory.posts;
$scope.PostCommand = function(){
    $scope.posts.comments.push({
        "comment":$scope.comment,
        "like":0
    });
};

如何添加评论?如果用户选择添加哪一个 我使用路由器也许$ stateParams帮助我?

1 个答案:

答案 0 :(得分:1)

我这样做:

<body ng-app="app">
    <div ng-controller="mainCtrl">
      <div ng-repeat="(key, post) in posts">
        {{post.text}}
        {{post.date}}
        <a href="#" ng-click="postLike(key)">Like {{post.like}}</a>
        <form>
            <input type="text" ng-model="newcomment[key].comment">
            <button ng-click="postCommand(key)">Add Comment</button>
        </form>
        <ul>
          <li ng-repeat="(keyC, item) in post.comments">
              {{item.comment}} <br/>
              <a href="#" ng-click="commentLike(key, keyC)"><i class="glyphicon glyphicon-thumbs-up"></i> Like {{item.like}}</a>
          </li>
        </ul>
      </div>
    </div>
  </body>

功能:

var app = angular.module('app', []);
app.controller("mainCtrl", function($scope){

    $scope.posts = [
      {
          "text":"text",
          "date":null,
          "like":0,
          "comments":[
              {"comment":"Yorum 1", "like":100},
              {"comment":"Yorum 2", "like":200},
              {"comment":"Yorum 3", "like":300}
          ]
      },
      {
          "text":"text2",
          "date":null,
          "like":0,
          "comments":[
              {"comment":"Yorum 4", "like":500},
              {"comment":"Yorum 5", "like":600}
          ]
      }
    ];

    $scope.postLike = function(key) {
      var like = $scope.posts[key].like;
      like = ($scope.posts[key].like == 1) ? 0 : 1 ;
      $scope.posts[key].like = like;
    };

    $scope.newcomment = {};
    $scope.postCommand = function(key){
      $scope.posts[key].comments.push($scope.newcomment[key]);
      $scope.newcomment = {};
    };

    $scope.commentLike = function(key, keyC) {
      var like = $scope.posts[key].comments[keyC].like;
      like = ($scope.posts[key].comments[keyC].like == 1) ? 0 : 1 ;
      $scope.posts[key].comments[keyC].like = like;
    };
});