0

Have created a directive to dynamically include the header.html in the master index html file.

app.js

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

app.directive('header', function() {

        var directive = {};
        directive.restrict = 'AE';
        directive.replace = true;
        directive.scope = {};
        directive.templateUrl = "header.html";
        directive.link = function postLink($scope, $element, $attrs, $resource) {
                  $scope.version = "1.1.1.1";
                  $scope.getusername = function() {
              $scope.username = "pals";
              };
              };
        return directive;
});

header.html

<div ng-init="getusername()">
  <p>
    This part of the hader is always here
  </p>
  <p>
    User {{username}} is logged in :D
  </p>
  <p>
  {{version}}
  </p>
</div>

Complete code written @ http://plnkr.co/edit/Iau6Fu?p=preview

The scope variable ($scope.version) is working.

But the scope function call ($scope.getusername) is not happening.

Any advice is appreciated. Thanks.

1 Answer 1

1

The code relies on ngInit in the template to execute a method called getusername() on the scope. getusername() is placed on the scope in the post-link function, which is executed after ngInit is evaluated. So ngInit never invokes getusername().

To fix this, place getusername() on the scope in the directive's controller so it is available to ngInit...

directive.controller = function($scope) {
    $scope.getusername = function() {
        $scope.username = "pals";
    };
};

Plunker

Please place the relevant code in your question rather than in a plunker.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.