在ng重复内编辑功能

时间:2014-10-14 17:12:02

标签: javascript angularjs

我在ng-repeat内部有一个编辑控件,可以正确更改布尔值,但是,通过ng-show挂钩到这些值的元素不会显示/隐藏。出了什么问题?

控制器:

    $scope.editedAnswers = {};

    $scope.toggleEditAnswer = function(answer) {
      $scope.editedAnswers[answer._id] = !$scope.editedAnswers[answer._id];
      console.log($scope.editedAnswers[answer._id]);
    };

    $scope.updateAnswer = function(answer) {
      answer.$update(function() {
        $location.path('answers/' + answer._id);
      });

      $scope.toggleEditAnswer(answer);
    };

HTML:

<div class="answers" ng-show="showAnswers">
      <div ng-repeat="answer in answers">
        <div class="answer-info">
          <a ng-show="!editedAnswer[answer._id]" ng-click="toggleEditAnswer(answer)">edit</a>
          <a ng-show="editedAnswer[answer._id]" ng-click="updateAnswer()">save</a>
        </div>

        <div ng-hide="editedAnswer[answer._id]"></div>
        <textarea ng-show="editedAnswer[answer._id]">
        {{answer.content}}
        </textarea>
      </div>
    </div>

2 个答案:

答案 0 :(得分:2)

问题是在控制器中定义editedAnswers属性,但在HTML中你引用editedAnswer属性(不带 - s

答案 1 :(得分:0)

尝试改变这一点:

<div class="answers" ng-show="showAnswers">
      <div ng-repeat="answer in answers">
        <div class="answer-info">
          <a ng-show="!editedAnswer[answer._id]" ng-click="toggleEditAnswer(answer)">edit</a>
          <a ng-show="editedAnswer[answer._id]" ng-click="updateAnswer()">save</a>
        </div>

        <div ng-hide="editedAnswer[answer._id]"></div>
        <textarea ng-show="editedAnswer[answer._id]">
        {{answer.content}}
        </textarea>
      </div>
    </div>

到此:

<div class="answers" ng-show="showAnswers">
      <div ng-repeat="answer in answers">
        <div class="answer-info">
          <a ng-show="answer._id != editedAnswer[answer._id]" ng-click="toggleEditAnswer(answer)">edit</a>
          <a ng-show="answer._id == editedAnswer[answer._id]" ng-click="updateAnswer()">save</a>
        </div>

        <div ng-hide="answer._id == editedAnswer[answer._id]"></div>
        <textarea ng-show="answer._id == editedAnswer[answer._id]">
        {{answer.content}}
        </textarea>
      </div>
    </div>

在您的版本中,您只需显示editedAnswer[answer._id]是否存在。

在我的编辑中(可能没有评估你真正想要的东西 - 你可能需要更改!=和==左右)我正在检查当前answer是否等于(或不)然后{{1} } - IE editedAnswer[answer._id]