Angular.js How to change an elements css class on click and to remove all others

前端 未结 6 1601
南旧
南旧 2020-12-22 17:27

i\'m trying to make my two elements toggle, so if one element is clicked it will remove all references of my-class and apply it to its self. Any ideas?



        
6条回答
  •  一向
    一向 (楼主)
    2020-12-22 18:10

    To me it seems like the best solution is to use a directive; there's no need for the controller to know that the view is being updated.

    Javascript:

    var app = angular.module('app', ['directives']);
    
    angular.module('directives', []).directive('toggleClass', function () {
        var directiveDefinitionObject = {
            restrict: 'A',
            template: '',
            replace: true,
            scope: {
                model: '='
            },
            transclude: true,
            link: function (scope, element, attrs) {
                scope.localFunction = function () {
                    scope.model.value = scope.$id;
                };
                scope.$watch('model.value', function () {
                    // Is this set to my scope?
                    if (scope.model.value === scope.$id) {
                        scope.selected = "active";
                    } else {
                        // nope
                        scope.selected = '';
                    }
                });
            }
        };
        return directiveDefinitionObject;
    });
    

    HTML:

    Click a span... then click another

    span1
    span2
    span3

    CSS:

    .active {
         color:red;
     }
    

    I have a fiddle that demonstrates. The idea is when a directive is clicked, a function is called on the directive that sets a variable to the current scope id. Then each directive also watches the same value. If the scope ID's match, then the current element is set to be active using ng-class.

    The reason to use directives, is that you no longer are dependent on a controller. In fact I don't have a controller at all (I do define a variable in the view named "model"). You can then reuse this directive anywhere in your project, not just on one controller.

提交回复
热议问题