Angular Boilerplate - Self transclusion

Boostrap tooltip dynamic text

by Silvestrs Kante

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/css/bootstrap.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.js"></script>
<div style="margin-top: 50px;" ng-app="myApp">
  <div ng-controller="MyCtrl">
    <input type="text" test-transclude error="error" ng-model="foo" property="first" />


    <input type="text" ng-model="error" />

    <p>
      {{ foo }}
    </p>

    <input type="text" test-transclude error="error" ng-model="bar" property="second" />

    <p>
      {{ bar }}
    </p>

  </div>
</div>

JavaScript

angular.module('myApp', ['ui.bootstrap']);

// Controller
(function(angular) {
  "use strict";

  angular
    .module('myApp')
    .controller('MyCtrl', MyCtrl);

  MyCtrl.$inject = ['$scope'];

  function MyCtrl($scope) {

    $scope.foo = "bar";
    $scope.bar = "cool";
    $scope.error = "zar";

  }

})(angular);

// Directive
(function(angular) {
  "use strict";

  angular
    .module('myApp')
    .directive('testTransclude', testTransclude);


  function testTransclude($compile) {

    var directive = {
      restrict: 'A',
      link: link,
      transclude: true,
      controller: function() {
        this.message = "";
      },
      controllerAs: 'ctrl',
      scope: {
        error: "=error",
        property: "@"
      }
    }

    return directive;

    function link(scope, element, attr, ctrl, transclude) {

      transclude(scope, function(clone, transScope) {
        element.removeAttr("test-transclude");
        element.attr('tooltip', '{{ ctrl.message }}');
        element.attr('tooltip-placement', 'top');
        element.append(clone);
        $compile(element)(transScope);
      });

      scope.$watch('error', function(value) {
        if (value == scope.property) {
          ctrl.message = "There is an error here";
        } else ctrl.message = "";
      })
    }
  }

})(angular);