user2024080
user2024080

Reputation: 5101

How to use `ng-bind` in directive for sorting the values

I am getting the collection from controller to directive. where I am appending to template.

i required to achieve 2 things here

  1. On load the collection - let it be sorted
  2. On input change, ( model change ) requried to re-sort the array values.

for my try both not works. any one clarify the issue here and sort the issue?

here is my code :

   app.directive("customGrid", function($timeout,$filter){
  return{
    scope:{ 
      "pages":"="
    },
    template:temp.join(''),
    link : function( scope, element, attrs ){
      scope.slice = null;

      scope.sortIt = function( value ){
        scope.pages.pin = $filter('orderBy')( value, '');
        console.log( scope.pages.pin ); 
//consoles sorted not updating in view
        scope.$apply(); 
      }

      $timeout(function(){
       scope.slice = scope.pages.pin;

       scope.sortIt( scope.slice );

      })

    }
  }
})

Live Demo

Upvotes: 1

Views: 318

Answers (1)

Michał Sałaciński
Michał Sałaciński

Reputation: 2266

How about that? using native angular sort with own filter, also passed whole objects to directive, as it might be tricky to work there with 3 separate, flat arrays. plnkr

var temp = [
  "<ul><li ng-repeat='obj in slice | myOrder:obj:reverse'>",
  "<input ng-model='obj.pin' type='text'/></li></ul>"
  ]

app.filter('myOrder', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (parseInt(a.pin) > parseInt(b.pin) ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});



app.directive("customGrid", function($timeout,$filter){
  return{
    scope:{ 
      "pages":"="
    },
    template:temp.join(''),
    link : function( scope, element, attrs ){
      scope.slice = null;
      $timeout(function(){
       scope.slice = scope.pages;
       console.log(scope.slice,scope.pages)
      })


      //console.log( sorted ); //not sorting
    }
  }
})

EDIT Plnkr without orderBy Still, it's hard to say without knowing details& requirements of the project. I can say, from own experience, it's often better to use some virtual-repeat techniques (or, in the case of tables, some dedicated vanilla scripts that work with Angular).

Upvotes: 1

Related Questions