codeandcloud
codeandcloud

Reputation: 55278

Override ng-hide on ng-click

On the process of trying to learn angularjs, I am creating a set of divs using ng-repeat. I have five divs in all. I am only displaying the first div using $firstdirective component.

<div class="container" ng-app="demoApp" ng-controller="demoController">
  <div class="row" ng-repeat="job in jobs" ng-hide="!$first">
    <div class="col-md-4">
      {{job}}
    </div>
    <div class="col-md-4">
      <button class="btn-primary btn-xs add" ng-click="showNext($event)" ng-hide="$last">Add</button>
      <button class="btn-primary btn-xs delete" style="display: none;">Delete</button>
    </div>
  </div>
</div>

That works.

Now, each div has two buttons, Add and Delete. When I click add I want to hide the add button and delete button of the current row and open the next row. So I wrote,

$scope.showNext = function(evt) {
  var elm = evt.target;
  $(elm).hide();
  $(elm).next().hide();
  $(elm).closest("div.row").next().slideDown();
};

This is not working as ng-hide is overriding my slideDown. What is the angularjs way of doing it?

Also I would like the delete button only on the $last visible row && !first. How to find last visible row in ng-repeat?

Fiddle: https://jsfiddle.net/codeandcloud/u4penpxw/

Upvotes: 0

Views: 402

Answers (1)

Johannes Jander
Johannes Jander

Reputation: 5020

You shouldn't manipulate the DOM with things like $(elm).hide();, you should use ng-class= to let Angular add classes that hide or show the elements. If you switch your ng-repeat to ng-repeat="job in jobs track by $index", you could write something like that in your showNext()-function:

 $scope.showNext = function(index) {
      $scope.currentJob = $scope.jobs[index]
 }

and call it like ng-click="showNext($index) - of course you'd need to do some refactoring as well. But then you could write something like ng-class="{hidden: (job == currentJob}" to hide all buttons except in the current row.

There's a lot of good thoughts in this q&a: "Thinking in AngularJS" if I have a jQuery background?

Upvotes: 1

Related Questions