简体   繁体   中英

Angular directive only updating class on one directive

I created a directive to add classes to my table filters th elements.

app.directive('tableFilter', function () {
return {
    link: function (scope, element, attrs) {
        element.html(attrs.text + ' <i class="fa fa-unsorted"></i>');
        icon = element.children();


        scope.$watch('reverse', function (oldVal, val) {
            console.log(icon);
            if (angular.isDefined(oldVal)) {
                console.log(val);
                if (val) {
                    icon.addClass('fa-sort-asc');
                    icon.removeClass('fa-sort-desc');
                } else {
                    icon.removeClass('fa-sort-asc');
                    icon.addClass('fa-sort-desc');
                }
            }
        });
    }
}
});

I have 2 th's where I use this directive. The HTML is as follows.

<tr>
    <th table-filter ng-click="tableFilter = 'name'; reverse=!reverse" text="Name"></th>
    <th table-filter ng-click="tableFilter = 'created'; reverse=!reverse" text="Date"></th>
</tr>

If I click on a th the class will be added and removed, but only to the th where text="Date". Everything goes right, except that the directive only adds or removes the class on the last th.

It is possible that this has something to do with the element.children()?

Hope you can help me.

Thanks in advance!

It is because of the icon = ... .

Defining it that way, makes icon a global, so every time you call icon = element.children() , icon will be updated with that element's children.

You should make it a local variable, like this:

var icon = ...;

<fun-spoiler>
Not directly related to your question, but there are still several problems with your implementation.
Eg:
1. The arguments to $watch() 's callback are reversed (as Sunil D mentioned), ie newVal comes before oldVal .
2. Upon clicking on a th , all icons are updated (which won't make much sense to the user as they won't know which column the table is sorted by).
</fun-spoiler>


<major-fun-spoiler>
Demo implementation .
( Note: It is not a good idea to have a reusable component such as table-filter share the scoe with its parent. It introduces tight coupling. You should use an isolate scope and create 2-way data-binding for tableFilter and reverse . But that's another story...)
</major-fun-spoiler>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM