Search code examples
angularjsangularjs-directiveangularjs-ng-clickng-hideangularjs-ng-show

multiple function on ng-click angularjs


I'm new to AngularJs and learning now, in my current assignment I need to achieve multiple things on ng-click.

  1. To hide and show some DOM elements based on the ng-click

  2. Change the background of the element where the ng-click is applied on, I'm trying to acheive this using a directive.

Mark-up:

    <div class="catFilter f6" ng-click="showSubCat = !showSubCat;toggleDropDown()">
        Choose A Genre
    </div>

    <div class="inactive" ng-show="showSubCat" ng-click="hideSubCat = !hideSubCat" ng-hide="!hideSubCat">
    </div>
    <div class="cat-drop-menu-list" ng-show="showSubCat" ng-hide="!hideSubCat">
    </div>

angular directive

retailApp.directive('toggleDropDown', function() {
return function(scope, element, attrs) {
    $scope.clickingCallback = function() {
        element.css({'background':'url("../images/down-arrow.png") no-repeat 225px 12px;'});
    };
    element.bind('click', $scope.clickingCallback);
}
});

Issues:

I'm not able to see the directive being applied, i.e., when I click on choose a genre, it is hiding and showing the other two divs, but not changing the back ground.


Solution

  • You can do this a couple ways, with bindings or directives:

    http://jsfiddle.net/abjeex75/

    var app = angular.module('app', []);
    
    app.controller('AppCtrl', function ($scope) {
        $scope.show_sub_cat = false;
    
        $scope.show = function () {
            $scope.show_sub_cat = true;
        }
    
        $scope.hide = function () {
            $scope.show_sub_cat = false;
        }
    });
    
    app.directive('toggleBg', function () {
        var directive = {
            restrict: 'A',
            link: link
        }
    
        return directive;
    
        function link(scope, element, attr) {
            element.on('click', function () {
                element.toggleClass('red');
            });
        }
    });