connectwithpalaniappan
connectwithpalaniappan

Reputation: 973

angularjs directive scope function not working

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.

Upvotes: 0

Views: 1564

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37550

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.

Upvotes: 1

Related Questions