Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <h1><a href="http://stackoverflow.com/questions/21290748/how-do-i-conditionally-add-an-attribute-directive-to-a-child-directive">Stackoverflow example directive problem</a></h1>
  <div ng-controller="MainCtrl">
    <h2>MainCtl</h2>
    showIt: {{showIt}}
    
    <h2>A directive dynamically adding `value` directive</h2>
    
    <a-directive show-it="showIt"></a-directive>
    <h2>Example of a static use of `value` directive</h2>
    <div value="static value"></div>
  </div>
</body>
</html>
 
(function(angular) {
  "use strict";
  
  var app = angular.module("app", []);
  
  app.controller('MainCtrl', [
    "$scope",
    function(
     $scope   
    ) {
      $scope.showIt = true;
    }
  ]);
  
  app.directive('aDirective', [
    function(
    ) {
      return {
        restrict: 'E',
        template: "<inner-directive></inner-directive>",
        link: function(scope, element, attrs) {
        },
        controller: [
          '$scope',
          function(
            $scope
          ) {
          }
        ]
      };
    }
  ]);
  
  app.directive('innerDirective', [
      "$compile",
    function(
      $compile
    ) {
      return {
        restrict: 'E',
        template: "<div>showIt: {{showIt}}</div>",
        /*link: function(scope, element, attrs) {
          
          // How do I conditionally add an attribute directive?
          if (scope.showIt) {
            element.attr("value", "hello");
            // This kills the browser
            // $compile(element)(scope);
          }
        } */
        link: {
          pre: function preLink(scope, iElement, iAttrs, controller) { 
            if (scope.showIt) {
              iElement.attr("value", "conditional value");
              
              // Add value if it hasn't already been added
              if (!iElement.attr.value) {
                // Creates an infinite loop and kills the browser
                //$compile(iElement)(scope);  
              }
            }            
          },
          post: function postLink(scope, iElement, iAttrs, controller) {
          }
        }
      };
    }
  ]);
  
  app.directive('value', [
    function(
    ) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.append("<div>" + attrs.value + "</div>");
        }
      };
    }
  ]);
})(angular);
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
taktranpro
0viewers