J
J
John2015-12-26 14:58:47
JavaScript
John, 2015-12-26 14:58:47

Directive execution?

There is a directive that switches the class:

myApp.directive('toggleClass', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.toggleClass(attrs.toggleClass);
            });
        }
    };
});

How to make it so that when clicking on a button with the .add class, the directive is executed not for this button, but for the element with the .hide-elements class?
<div class="hide-elements"></div>
    <button class="add">+</button>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-12-26
Galt @Fargal_1

use ng-click and state binding, don't work with the DOM yourself.
The whole point of angular is in the declarative view, that is, no attempts to change something in the DOM on their own.

<div class="hide-elements" ng-class="{'your-class-name': vm.some.condition}"></div>
    <button class="add" ng-click="vm.add()">+</button>

in the controller you change the state of the component and everything is fine.
Let me explain why this is good. If your application does not have a DOM binding and it operates with primitives that Angular provides you (ngHide / ngShow / ngClass / ngRepeat, etc.), then you do not need to worry at all about how the view is formed. The possibility of side effects is reduced, there is no need to cover the code with tests (well, or worry that something will break just like that), it is enough to check that the application enters the required state, and Angular already guarantees that the view will adapt to this state as you declared it in the templates .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question