Ya Basha
Ya Basha

Reputation: 1952

angularjs template binding

I have developed a transclude directive and I set it to use angularjs template script everything works fine but I still cannot access the bind data.

My code:

index.html

<div side-element="box" title="Links">
                <ul>
                    <li>Link 1</li>
                    <li>Link 2</li>
                </ul>
</div>

<script id="box" type="text/ng-template">
            <div class="side-box">
                <div class="content">
                    <h2 class="header">Box {{ title }}</h2>
                    <span class="content" ng-transclude></span>
                </div>
            </div>
        </script>
        <script id="ad" type="text/ng-template">
            <div class="side-ad">
                <div class="content">
                    <h2 class="header">AD {{ title }}</h2>
                    <span class="content" ng-transclude></span>
                </div>
            </div>
        </script>

app.js:

angular.module('myApp.directives')
  .directive('sideElement', function ($templateCache, $log) {
return {
  scope: {
    title: '@'
  },
  transclude: 'element',
  link: function(scope, element, attrs, ctrl, transclude){
    var template = $templateCache.get(attrs.sideElement);

    var templateElement = angular.element(template);
    $log.info(scope.title);//Output the title i put in the html which is (Links)
    transclude(scope, function(clone){
      element.after(templateElement.append(clone));
    });
  }
};
});

the scope inside the link function(....) displaies the correct title but it doesn't work in the html:

Box {{ title }}

Link 1 Link 2

I think I missed one thing but I can't figure it out, I need your help to complete the cycle.

Thanx in advance,

Upvotes: 0

Views: 1779

Answers (1)

Michael Kang
Michael Kang

Reputation: 52837

The template element that contains the angular binding expressions must be compiled first, and then linked. The compilation phase prepares the template, while the linking phase sets up your $watchers for your binding expressions.

Demo Here

Here is a compile function that should work:

    .directive('sideElement', function ($templateCache, $compile, $log) {

    return {
      restrict: 'A',
      transclude: true,
      scope:'@',
      compile: function(element, attrs) {
        var template = $templateCache.get(attrs.sideElement);
        var templateElement = angular.element(template);
        element.append(templateElement);
        return function(scope, element, attr, ctrl, transclude) {
          $log.info(scope.title);
        }
      }
    }

Upvotes: 2

Related Questions