In a <table>
header where labels can be clicked to order data in some specific way, I'm trying to replace this code :
<th>
<a class="sortable-th" href="#" data-ng-click="sortType = 'atSenderScheduledDate'; sortReverse = !sortReverse">
Date
<span data-ng-show="sortType == 'atSenderScheduledDate' && !sortReverse" class="md-chevron-down"></span>
<span data-ng-show="sortType == 'atSenderScheduledDate' && sortReverse" class="md-chevron-up"></span>
</a>
</th>
(where only one <span>
is displayed to show the sorting order) with a custom directive such as :
<th>
<th-sortable type="atSenderScheduledDate" label="Date"></th-sortable>
</th>
The Controller holds the sorting variables :
$scope.sortType = 'atSenderScheduledDate'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
And the directive is as follows :
(function() {
angular.module('app').directive('thSortable', thSortable);
thSortable.$inject = ['$parse'];
function thSortable($parse) {
return {
restrict : 'E',
scope : {
},
link : function(scope, elem, attrs) {
var type = attrs.type;
var label = attrs.label;
var newElem = '';
newElem += '<a class="sortable-th" href="#">';
newElem += ' ' + label;
newElem += ' <span class="md-chevron-up" data-ng-show="sortType === \'' + type + '\' && !sortReverse"></span>';
newElem += ' <span class="md-chevron-down" data-ng-show="sortType === \'' + type + '\' && sortReverse"></span>';
newElem += '</a>';
elem.append(newElem);
elem.bind('click', function() {
scope.$apply(function() {
$parse("sortType").assign(scope.$parent, type);
$parse("sortReverse").assign(scope.$parent, !scope.$parent.sortReverse);
});
});
}
};
}
})();
The click
binding is working as expected and the data is accurately being ordered. However, I can't manage to get the data-ng-show
part of the two <span>
's working, in order to only display the relevant one.
Any help would be appreciated, thanks.
elem.bind('click', function() {
scope.$apply(function() {
$parse("sortType").assign(scope.$parent, type);
$parse("sortReverse").assign(scope.$parent, !scope.$parent.sortReverse);
});
});
You are using $parse("sortType")
and $parse("sortReverse")
, not sure how would it update your parent scope properties
. Since your directive is an isolate scope, why don't you pull them in your scope like below and use it.
scope : {
sortType: "=",
sortReverse: "="
},
Then in your link function you can use scope.sortType
and scope.sortReverse
and also its much better to send object
to ng-model
as boolean
values would create a whole new scope inside your directive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.