jBoive
jBoive

Reputation: 1299

Dynamically changing a class for a directive in AngularJS?

I have a buch of movies, think Netflix. Each movie have a number of tags assigned to it: Comedy, Horror etc.

When I click on a tag the view is filtered accordingly, that works great. But what I also wish to do is to add a class to all the tags, with the same name (on every other movie), as the one clicked.

I could do an ugly jQuery :contains in the click-event, but that doesn't feel right.

I'm a AJS noob, but I'm sure there's a better AJS way of achieving this?

(function () {
var directive = function () {
    return {
        restrict: 'A',
        template: '<li data-ng-repeat = "tag in movie.genre">{{tag}}</li>',
        link    : function ($scope, element, attrs) {
            element.bind('click', function (e) {
                var linkText = e.target.innerText;

                if ($scope.$parent.category === linkText) {
                    return;
                }

                $scope.$parent.category = linkText;
                $scope.$apply();
            })
        }
    };
};

angular.module('videoApp')
    .directive('videoTags', directive);
}());

Upvotes: 0

Views: 1061

Answers (2)

jBoive
jBoive

Reputation: 1299

I'm still complicating things with AJS, the solution was very simple. Simply change the template property to:

template: '<li data-ng-class="{\'active\' : category === tag}" data-ng-repeat = "tag in movie.genre">{{tag}}</li>',

I didn't expect the "tag" variable to be available in other directives as well, but this is great! =)

Now, when a tag is clicked - every other movie with that same tag also get's the class set. Due to two-way data binding.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

You should use a two-way data binding between the controller that uses this directive and the selected category. In the controller you could have a selectedCategory property and for each movie in the list you can apply styles if selectedCategory matches. Then for the directive:

return {
    scope: {category: "=selectedCategory"}

I would also suggest using ng-click instead of element.bind but that shouldn't change functionality.

Upvotes: 1

Related Questions