Jiew Meng
Jiew Meng

Reputation: 88189

Angular directive scope variable undefined

I am trying to access my scope variables in link but they appear undefined

/** @ngInject */
function tablePagination() {
  return {
    restrict: 'E',
    template: require('./tablePagination.html'),
    scope: {
      currentPage: '=',
      totalPages: '=',
      totalCount: '=',
      perPage: '='
    },
    link: function (scope) {
      console.log(scope.currentPage, scope) // scope.currentPage is undefined
    }
  }
}

// controller for authlogin
module.exports = tablePagination

I also tried using @ rather than = and changed the binding to using {{}} but its still undefined. I could use $observe but I want to get values for multiple attributes at once to do some computation. Whats the best way to do this?

HTML Code

 <table-pagination
    current-page="$ctrl.tableMeta.currentPage"
    total-count="$ctrl.tableMeta.totalCount"
    total-pages="$ctrl.tableMeta.totalPages"
    per-page="$ctrl.tableMeta.perPage"></table-pagination>

UPDATE: I wonder if its because the directive is not getting updated values from $ctrl.tableMeta which is coming from API/Async

SOLUTION!: Oh I discovered my mistake was I need to use $watch otherwise it gets the old value which is by default undefined, since its not set async by API yet

scope.$watch('currentPage', () => {
  scope.start = (scope.currentPage - 1) * scope.perPage + 1
  scope.end = Math.min(scope.currentPage * scope.perPage, scope.totalCount)
})

Upvotes: 4

Views: 1228

Answers (1)

MMK
MMK

Reputation: 3721

Its just an example i hope it will clear few things up.

gridPagination.html

<label>current Page:</label><span>{{ currentPage }}</span>
<br>
<label>Total Pages:</label> {{ totalPages }}

app.js

var app = angular.module("myApp", []);

mainController.js

app.controller('mainController', ['$scope', function($scope) {
  $scope.title = 'My Grid';
}]);

gridDirective.js

app.directive('grid', gridPagination);

function gridPagination() {
  return {
    restrict: 'E',
    scope: {
      currentPage: '=',
      totalPages: '=',
      totalCount: '=',
      perPage: '='
    },
    templateUrl: 'gridPagination.html',
    link: function(scope, element, attrs) {
      console.log(scope.currentPage);
      console.log(scope.totalPages);
      console.log(scope.totalCount);
      console.log(scope.perPage);
    }
  };
};

index.html

<html>
  <head>
    <link rel="stylesheet" href="main.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
  </head>   
  <body ng-app="myApp">
    <div ng-controller="mainController">
        <grid current-page="3" total-pages= "30" total-count="10" per-page="2"></grid>
    </div>        
    <script src="app.js"></script>
    <script src="mainController.js"></script>
    <script src="gridDirective.js"></script>
  </body>    
</html>

plunker

Upvotes: 1

Related Questions