kellzerIrl
kellzerIrl

Reputation: 101

How to change the style of a individual element in an angular directive?

I am new to angular and here is the problem I am having. I have created a directive:

angular
.module('app.simpledirective')
.directive('simpledirective', function() {
    return {
        templateUrl: 'app/simpledirective/sample.html',
        bindToController: true,
        controller: SampleController
    };
});

function SampleController($scope) { }

//Here is the sample.html for this directive

<div class="outer">
    <div class="inner1">Show</div>
    <div class="inner2">Don't Show</div>
</div>

The problem I am having is, if I call this directive in 2 different places ie:

<div>
    <simpledirective></simpledirective>        
</div>

How can I make it that in one place it displays both classes, "inner1" and "inner2", but in the second place, it only shows class "inner1", ie "inner2" is hidden.

Thanks for any help!

Upvotes: 0

Views: 62

Answers (3)

Arkantos
Arkantos

Reputation: 6608

You can change your directive to accept attributes from your directive definition and use them to show/hide a particular div in your sample.html like below.

<div class="outer">
    <div ng-show="inner1" class="inner1">Show</div>
    <div ng-show="inner2" class="inner2">Don't Show</div>
</div>

app.js

angular
.module('app.simpledirective',[])
.directive('simpledirective', function() {
    return {
        scope : {
          inner1 : '@',
          inner2 : '@'
        },
        templateUrl: 'app/simpledirective/sample.html',
        bindToController: true,
        controller: SampleController
    };
});

main.html

<div>
    <simpledirective inner1="true"></simpledirective>        
</div>

If you want only inner1 to display, pass some value in directive and leave inner2. Note that if you pass inner2="false", even that is considered as a valid value and your 2nd div will be displayed. Just add the attribute value only for the div you wish to show.

Here's a sample pen illustrating the above idea :)

Upvotes: 1

vusan
vusan

Reputation: 5331

You can also do this by adding class on parent class like
Place 1.

<div>
    <simpledirective></simpledirective>        
</div>

Place 2.

<div class="inner2Hide">
    <simpledirective></simpledirective>        
</div>

css:

.inner2Hide .inner2 {
  display:none
}

Upvotes: 1

Chrillewoodz
Chrillewoodz

Reputation: 28318

You can try passing parameters to the directive:

return {
    scope: {
      inner1: '=', 
      inner2: '='
    },
    templateUrl: 'app/simpledirective/sample.html',
    bindToController: true,
    controller: SampleController
};

Pass them like so:

<simpledirective inner1="true" inner2="false"></simpledirective>

Then use ng-class to decide if the classes should be applied or not:

<div class="outer">
  <div ng-class="{inner1: inner1}">Show</div>
  <div ng-class="{inner2: inner2}">Don't Show</div>
</div>

Upvotes: 2

Related Questions