ng-click and ng-init variable definition

581 Views Asked by At

I am trying to make table header sorter work by using ng-click and ng-init.

Examples in angular js documents require modules, and if I install and update that module, my SPA falls apart for some reason. I tried to make it work, but even with help from other colleagues, it failed.

So, I thought of by-passing and came up with ng-click and ng-init. If I count the number of clicks, then every even number of click, the table sorts by ascending and every odd number of click, the table sorts by descending.

I can do one click and one sorting (e.g. one click - ascending - done for good no matter how much more I click) with (click). But, when I used ng-click and ng-init, the variable inside ng-init is not recognized.

<th><button class="some-type" ng-click="count = count + 1; oddEven(count)? sortByAsc(column) : sortByDes(column)" ng-init="count = 0"><b>columnName</b></button></th>

If I insert {{ count }} right besides columnName in the above code (or anywhere in the code for what's worth), it gives error saying count is not defined.

<th><button class="some-type" ng-click="count = count + 1" ng-init="count = 0"><b>columnName</b></button></th>

I removed additional function calls in ng-click like in the above code, but even this simple code does not recognize count at all.

So, is there specific way to declare variables inside ng-init and ng-click?

Why would this code not work the way it is?

1

There are 1 best solutions below

4
Kamran Qadri On

I suggest keeping an object tracking which col order is on acs or des order which you can use in function to call respective function. Here is the sample code.

var sortOrder = {
  column1: false,
  column2: false
}

$scope.sortBy = function(col) {
  if(sortOrder[col]) {
    sortByAsc(col)
  } else {
    sortByDes(col)
  }
  sortOrder[col] = !sortOrder[col]
}