Search code examples
javascriptjqueryangularjsangular-ng-if

ng-if condition not working properly [AngularJS]


When i click comment or reply link the form is opening up for all the cards. How to make to a particular scope such that the form should only open for which the link is clicked.

The below function is used with ng-if in the html to hide the form.Once clicked it should open only the corresponding form.

 $scope.increaseReply = function(object) {
   object.replyone += 1;
 };

Here is plukr link


Solution

  • You should assign replyActive bit for each comment. To do that, you can use iteration objects (I assumed you are using ng-repeat). You can add one more property to your object interactively and use it freely.

    Simple example;

    var myApp = angular.module('myApp',[]);
    
    function MyCtrl($scope) {
     	$scope.commentList = [
        	{
          	"author": "Tugca Eker",
            "comment": "You should check this example..."
          },
          {
          	"author": "Gagan",
            "comment": "ng-if not working"
          },
          {
          	"author": "Tugca Eker",
            "comment": "Check it again"
          }
        ];
      	
    }
    ul li{
      padding: 5px;
      border: 1px solid black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-controller="MyCtrl">
    
      <ul>
        <li ng-repeat="comment in commentList" ng-init="comment.isReplyActive = false;">
          <b>{{comment.author}}</b>: {{comment.comment}}
          <br />
          <a ng-click="comment.isReplyActive = !comment.isReplyActive;">Reply Now!</a>
          <div ng-if="comment.isReplyActive">
            <input type="text">
          </div>
        </li>
      </ul>
     
    </div>

    Snippet on Stackoverflow fails, I don't know why. Check this fiddle, http://jsfiddle.net/Lvc0u55v/7762/