Darama
Darama

Reputation: 3380

Why directive does not set class?

I tried to write custom directive Angular JS that sets class to element depending of incoming parametes:

angular.module('hello', [])
    .directive("testCase", function(){

   return {
        restrict: 'A',
        scope: {
            'condition': '='
        },
        link: function (scope, element, attrs) {
           switch (scope.condition) {
              case "pending":
                element.css('color', 'yellow');
                break;
              case 'active':
                element.css('color', 'green');
                break;
              case "archived":
              case "finished":
              case "completed":
                element.css('color', 'gray');
                break;
                }

        }
        }
});

http://jsfiddle.net/9h29R/71/

But directory does not set class, when I pass param "active"

Upvotes: 0

Views: 36

Answers (2)

Wilmer SH
Wilmer SH

Reputation: 1417

@Slava. K cought the error. Just for fun, here is another way of setting styles, and any other attribute on an element using attrs.$set:

The JS

angular.module('hello', [])
  .directive("testCase", function() {

    return {
      restrict: 'A',
      scope: {
        'condition': '='
      },
      link: function(scope, element, attrs) {

        var setStyle = function() {

          switch (attrs.condition) {

            case "pending":
              return "color: yellow"
            case "active":
              return "color: green"
            case "archived":
            case "finished":
            case "completed":
              return "color: gray"
          }
        };

        attrs.$set('style', setStyle());
      }

    }
  });

The Markup

<div ng-app="hello">
  <div test-case condition="active">Active</div>
  <div test-case condition="pending">Pending</div>
  <div test-case condition="archived">Archived</div>
  <div test-case condition="finished">Finished</div>
</div>

The Fiddler

http://jsfiddle.net/zh9u45nn/2/

Upvotes: 1

Slava.K
Slava.K

Reputation: 3080

You are just missing quotes. You need to pass string otherwise angular would compile active as a parent scope variable. Check the working fiddle: http://jsfiddle.net/9h29R/73/

<div ng-app="hello">
    <div test-case condition="'active'">Active</div>    
</div>

Upvotes: 1

Related Questions