Dynamically Add class to Element using AngularJS

1.6k Views Asked by At

I want to mimic something that I have done with JQuery using AngularJS.

Below is the fiddle for it.

Three things I have done here.

  1. Find the last element of the right column.
  2. Pickup the attribute 'data-color' from it
  3. Assign the value of the attribute as a class to the 'right-col'
2

There are 2 best solutions below

2
On BEST ANSWER

Try this JSFiddle: https://jsfiddle.net/ubqrah1w/

It uses an angular directive.

.directive('lastColor', function () {
  return {
    restrict: 'A',
    link: function ($scope, $element, $attrs) {
    $element.addClass(angular.element($element[0].querySelector('.items:last-child')).attr('data-color'));
    }
  }
  });
1
On

This can be done by angular'js directive (re-usable component) moreover angular has jqlite (jQuery library), as below.

directives:

app.directive('dynamicColor',dynamicColor);

    dynamicColor.$inject = [];

    function dynamicColor(){

      return{
        restrict:'A',
        link:function(scope,element,attrs){
          element.css('background-color',attrs.dynamicColor);
        }
      }

    }

https://plnkr.co/edit/Op5fI5oFQku07tkebBcg?p=preview