0

我正在尝试编写一个指令,它将在我的应用程序的任意位置对任意数据进行排序。让我们说我有以下代码(根据实际真正的代码,排序函数和一些用于简化复杂的)包装为指令的通用功能

angular.module('test', []); 
angular.module('test').controller('wrapperController',['$scope', function(scope){ 
    scope.data = {} 
    scope.data.rows = [{name: 'foo'}, {name: 'bar'}, {name: 'bazz'}] 
    scope.data.columns = [{name: 'Name', sortBy: 'name'}] 
}]); 
angular.module('test').directive('grid', [function(){ 
    return { 
    restrict: 'A', 
    templateUrl: 'grid.html', 
    scope: { 
     grid: '=' 
    } 
    } 
}]); 
angular.module('test').directive('sortable', [function(){ 
    return { 
    restrict: 'A', 
    scope: { 
     sortableCollection: '=', 
     sortableKey: '&' 
    }, 
    compile: function(el, at, transclude){ 
     if(at['ng-click']){ 
     el.attr('ng-click', el.attr('ng-click')+';sortFunction()') 
     }else{ 
     el.attr('ng-click', 'sortFunction();') 
     } 
     return(function(scope, element, attrs){ 
     scope.sortableKey = scope.sortableKey(); 
     scope.sortFunction = function(){ 
      alert(" I AM IN UR FUCNTION SORTING UR D00dZ!!1"); 
     } 
     }); 
    } 
    } 
}]); 

而且下面的HTML:

<body ng-app='test'> 
    <div ng-controller='wrapperController'> 
     <div grid='data'></grid> 
    </div> 
    </body> 

和(在grid.html):

<div> 
    <table> 
    <thead> 
     <tr> 
     <td ng-repeat='column in grid.columns'> 
      <div sortable sortable-collection='grid' sortable-key='column.sortBy'>{{column.name}}</div> 
     </td> 
     </tr> 
    </thead> 
    <tbody> 
     <tr ng-repeat='row in grid.rows'> 
     <td ng-repeat='cell in grid.columns'> 
      {{row.name}} 
     </td> 
     </tr> 
    </tbody> 
    </table> 
</div> 

检查的HTML显示,ng-click正确填充,但是当标题被点击的功能永远不会触发。这是为什么?有没有办法获得这种行为?

plunr:http://plnkr.co/edit/aXjMqhZxI7ME8wQJOLpA?p=preview

回答

3

只是简单的增加没有按属性不要让角色去执行那个指令。当angular启动应用程序时,它会扫描DOM指令。然后它调用它们的编译函数。因此,如果在该功能中添加ng-click,则为时已晚。

在指令中添加ng-click无论如何都没有意义。您想为click事件添加事件侦听器。

link: (function(scope, element, attrs){ 
    scope.sortableKey = scope.sortableKey(); 
    element.on('click', function(){ 
     alert(" I AM IN UR FUCNTION SORTING UR D00dZ!!1"); 
     // call $scope.apply(); after you have changed the model 
    }); 
+0

+1,完美。当然绑定点击。我在ng-click上挂了太多。 –

1

网格指令可以创建在其范围control object

link: function(scope, element, attrs) { 
    scope.sorter = {}; 
} 

,并把它传递给排序指令:

<div sortable sort-control='sorter'...></div> 

的排序指令将随后加对控制对象的排序功能:

scope: { 
    .... 
    sortControl: '=' 
}, 
link: function(scope, element, attr) { 
    if (scope.sortControl) { 
    scope.sortControl = { 
     sortFunction: function() { 
     alert(" I AM IN UR FUCNTION SORTING UR D00dZ!!1"); 
     } 
    }; 
    } 
} 

最后,回到网格模板,我们可以访问排序功能作为我们的控制对象的属性:

<div sortable ng-click='sorter.sortFunction()' sort-control='sorter'...></div> 

这里是一个工作演示:http://plnkr.co/edit/iYkVbh2wGfCWBWA0SX3M?p=preview

+1

这是有点hawt,我记得这种方法供将来参考。谢谢! –