Javascript 角形don';t排序数据
我尝试用角度对数据进行排序。 这是我的代码:Javascript 角形don';t排序数据,javascript,angularjs,Javascript,Angularjs,我尝试用角度对数据进行排序。 这是我的代码: <table id="data-table" width="100%" class="table table-striped table-hover"> <thead> <tr> <th class="sortable" field="name">Name</th> <t
<table id="data-table" width="100%" class="table table-striped table-hover">
<thead>
<tr>
<th class="sortable" field="name">Name</th>
<th class="sortable" field="phone">Phone number</th>
</tr>
</thead>
<tbody>
<tr class="tr-data" ng-repeat="el in list | orderBy:sortCol:sortType" >
<td>{{el.name}}</td>
<td>{{el.phone}}</td>
</tr>
</tbody>
</table>
<div>{{sortType}}</div>
<div>{{sortCol}}</div>
名称
电话号码
{{el.name}
{{el.phone}}
{{sortType}}
{{sortCol}}
javascript:
var someData = [
{'name': 'Vasja', 'phone': '00375 29 654 1185'},
{'name': 'Sasha', 'phone': '00375 29 654 1176'}];
app.controller('myCtrl', function($scope)
{
$scope.sortType = false;
$scope.sortCol = 'phone';
$scope.list = someData;
$scope.applySort = function()
{
$('th.sortable').each(function(idx, el)
{
var uarr = $('<span class="sort-span" ng-click="xSort(this);">↑</span>');
var darr = $('<span class="sort-span">↓</span>');
uarr.appendTo(el).on('click', function() { $scope.sortCol = $(el).attr('field'); $scope.sortType = false;});
darr.appendTo(el).on('click', function() { $scope.sortCol = $(el).attr('field'); $scope.sortType = true;});
});
};
$scope.applySort();
});
var someData=[
{'name':'Vasja','phone':'00375296541185'},
{'name':'Sasha','phone':'00375296541176'};
应用程序控制器('myCtrl',函数($scope)
{
$scope.sortType=false;
$scope.sortCol='phone';
$scope.list=someData;
$scope.applySort=function()
{
$('th.sortable')。每个(函数(idx,el)
{
变量uarr=$('↑');
var darr=$('↓');
uarr.appendTo(el).on('click',function(){$scope.sortCol=$(el).attr('field');$scope.sortType=false;});
darr.appendTo(el).on('click',function(){$scope.sortCol=$(el.attr('field');$scope.sortType=true;});
});
};
$scope.applySort();
});
通过单击箭头-没有任何更改。即使数据sortCol和SortType也没有更改。
但是,当我在列表中更改数据时,排序正在应用;Angular无法通过jquery事件触发它的事件。或者您可以在jquery事件的末尾添加
$scope.$apply()
,这会起作用,但这不是一个好的解决方案
更好的方法是在angular中呈现箭头,并用angular绑定事件。不要使用jQuery,应该使用angular指令,如ngClick:
<thead>
<tr>
<th class="sortable" field="name">
Name
<span class="sort-span" ng-click="sort('name', false)">↑</span>
<span class="sort-span" ng-click="sort('name', true)">↓</span>
</th>
<th class="sortable" field="phone">
Phone number
<span class="sort-span" ng-click="sort('phone', false)">↑</span>
<span class="sort-span" ng-click="sort('phone', true)">↓</span>
</th>
</tr>
</thead>
谢谢。好主意,但我更喜欢使用最少的代码,我的解决方案是通用的。$scope.$apply()-酷。
app.controller('myCtrl', function ($scope) {
$scope.sortType = false;
$scope.sortCol = 'phone';
$scope.list = someData;
$scope.sort = function (field, type) {
$scope.sortCol = field;
$scope.sortType = type;
};
});