角度指令评论部分

时间:2014-04-22 12:56:00

标签: angularjs

我正在一个展示大量文章的网站上工作。每篇文章都有一个评论部分。我已经有效地能够递归地将注释写入DOM,并在ng-repeat中进行递归。但是,我需要能够单击任何注释上的响应按钮(它们以嵌套方式显示),并且可以在单击的按钮下方插入div。这个div将包含他们想要提交的评论的文本区域和一个按钮。单击此第二个按钮时,控制器将注释保存到数据库。我最初想通过直接操纵控制器中的DOM来做到这一点。但是,经过进一步的研究,这将直接违反MVC / MVW模式。我相信正确的答案是创建一个自定义指令。请给我一些关于如何正确执行此操作的见解。任何和所有信息都会非常有用。提前谢谢。

2 个答案:

答案 0 :(得分:0)

你真的不需要制定指令来实现这一目标。

HTML:

<div ng-repeat="article in articles">
  <p>{{article.content}}</p>
  <input type="text" ng-model="article.response"></input>
  <button ng-click="sendResponse(article)">Send</button>
</div>

JS:

myApp.controller("articlesController", function($http){

  $scope.sendResponse = function (article) {
    console.log(article.response);
    $http.post(url, article);
  };
});

当然,你可以通过隐藏输入和发送按钮来做得更好,并在用户点击答案按钮后显示它。

答案 1 :(得分:0)

如果要动态添加响应div:

<div ng-repeat="article in articles" id="article-{{$index}}">
  <p>{{article.content}}</p>
  <button ng-click="addAnswer($index)">Add Answer</button>
</div>

是:

myApp.controller("articlesController", function($compile){
  $scope.addAnswer = function (index) {
     var div = $("<div></div>");
     var input = $("<input type='text' ng-model='article.response'></input>");
     div.append(input);
     var button = $("<button>Send</button>");
     button.attr("ng-click", "sendResponse(article)");
     $compile(div)($scope);
     $("#article-" + index).append(div);
  };
});
相关问题