Search code examples
angularjsangular-directiveangularjs-ng-transclude

ngTransclude directive doesn't work, can't realize where I'm wrong


Trying to use ngTransclude first time to make custom directive, to achieve the floating label functionality as shown here: Floating label pattern — Angular JS, but it doesn't work.

Here is my directive code:

.directive('floatingLabel', function () {
        return {
            restrict: 'A',
            scope: {
                label: '@',
                value: '='
            },
            transclude: true,
            templateUrl: 'floating-label-template.html'
        }}
 )

Directive's template:

<div class="field">
      <label ng-show="value" class="show-hide">{{label}}</label>
      <div ng-transclude></div>
 </div>

I'm trying to use it in the following way:

<input floating-label label="Floating" value="floatingDirective"  type="text" class="form-control" ng-model="floatingDirective"/>

Plunker with my code: https://plnkr.co/edit/MC8G4H3B9zEleaBZ7ijJ?p=preview

P.S. I'm using AngularJS 1.4.9


Solution

  • Fixed plunker.

    Read this : What is ng-transclude

    Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.

    Why your code not working: you have nothing to be 'transclude'.

    A general markup of use directive with ng-transclude may like this:

    <directive-with-ng-transclude>
      <node-to-transclude></node-to-transclude>
    </directive-with-ng-transclude>
    

    After compiled, <node-to-transclude></node-to-transclude> will be appended to the template of your directive where you put ng-transclude.

    Notice : ng-model inside ng-transclude , that's why I use a dotted ng-model floatingDirective.