ng-class 初始页面加载不正确
ng-class not correct on initial pageload
这个问题让我很沮丧。
加载页面时,table 的默认排序是通过以下代码设置的:
$scope.sort = {
field: 'date',
dir: 'asc'
};
通过用户点击 table 标题更改排序,如下所示:
<th ng-class="{'sort-desc': sorted('date', 'desc'), 'sort-asc': sorted('date', 'asc')}" class="sortable">
<a href="#" ng-click="setSort('date')">Date</a>
</th>
这是 setSort 代码:
$scope.setSort = function(field) {
if ($scope.sort.field == field)
$scope.sort.dir = ($scope.sort.dir == 'desc') ? 'asc' : 'desc';
else
$scope.sort.field = field;
$scope.update();
};
并排序
$scope.sorted = function(field, dir) {
return ($scope.sort.field == field && $scope.sort.dir == dir);
};
在初始页面加载时,默认排序 (date-asc) 应用于 table 中的数据,但不应用 sort-asc。
更改排序列时,它会显示正常 - 这只是初始页面加载。
如何让 angular 在页面加载时正确评估?
经过一番摸索,我发现了问题所在:我 $scope.sort
定义了两次,一次作为对象,一次作为函数。
出于某种原因,它在通过更改排序重新定义 $scope.sort.dir
和 $scope.sort.field
后工作,但原始值被我的函数定义覆盖。
经验教训 - 对变量名称要更加小心。
这个问题让我很沮丧。
加载页面时,table 的默认排序是通过以下代码设置的:
$scope.sort = {
field: 'date',
dir: 'asc'
};
通过用户点击 table 标题更改排序,如下所示:
<th ng-class="{'sort-desc': sorted('date', 'desc'), 'sort-asc': sorted('date', 'asc')}" class="sortable">
<a href="#" ng-click="setSort('date')">Date</a>
</th>
这是 setSort 代码:
$scope.setSort = function(field) {
if ($scope.sort.field == field)
$scope.sort.dir = ($scope.sort.dir == 'desc') ? 'asc' : 'desc';
else
$scope.sort.field = field;
$scope.update();
};
并排序
$scope.sorted = function(field, dir) {
return ($scope.sort.field == field && $scope.sort.dir == dir);
};
在初始页面加载时,默认排序 (date-asc) 应用于 table 中的数据,但不应用 sort-asc。 更改排序列时,它会显示正常 - 这只是初始页面加载。
如何让 angular 在页面加载时正确评估?
经过一番摸索,我发现了问题所在:我 $scope.sort
定义了两次,一次作为对象,一次作为函数。
出于某种原因,它在通过更改排序重新定义 $scope.sort.dir
和 $scope.sort.field
后工作,但原始值被我的函数定义覆盖。
经验教训 - 对变量名称要更加小心。