1

So I can't really get this to work, I've got the following code

HTML:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  {{vt.t}} 
  <div my-directive="{{vt.t}}"></div>
  {{vt.f}}
  <div my-directive="{{vt.f}}"></div>

  <hr />

  {{vt.t}} 
  <div ng-class="{'my-directive': vt.t}"></div>
  {{vt.f}}
  <div ng-class="{'my-directive': vt.f}"></div>

  <hr />

  <div class="my-directive"></div>
  <div class="nodirectiveclass"></div>

</body>
</html>

JavaScript:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.vt = { t: true, f: false };
});

app.directive('myDirective', function($compile) {
  return {
    restrict: 'AC',
    template: '<div>Directive on</div>',
    replace: true
  };
});

Plunker: http://plnkr.co/edit/7cJKhIuNqnsk1CkczjoE?p=preview

As you see the classes doesn't trigger the directive when added dynamically but works fine in my last "static" example. I also tried setting the directive attribute to true or false but that didn't seem to help.

niksvp
  • 5,545
  • 2
  • 24
  • 41
Hultner
  • 3,710
  • 5
  • 33
  • 43
  • This is because ng-class set the class after the compilation process, everything is explained here: http://stackoverflow.com/a/18599528/1062711 – ex0ns Jul 30 '14 at 11:28
  • Workaround would depend on what directive does. Might be able to use `ng-if` or `ng-switch` or may have to put more logic in directive depending on use – charlietfl Jul 30 '14 at 12:13

1 Answers1

0

I think you should use model variable in your directive. Then you can access what ever the value you want easily.

Refer this Answer: AngularJS - Create a directive that uses ng-model

Community
  • 1
  • 1
Sankalpa
  • 41
  • 5