0

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);
}());

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I gave you a vote for effort, but I've chosen another solution.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.