Angular scope variable undefined

I try 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 @, not =changing the binding using {{}}, but still undefined. I could use $observe, but I want to immediately get the values ​​for several attributes to do some calculations. What is 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>

The UPDATE . I wonder if it is because the directive does not get updated values ​​from $ctrl.tableMetathat come from API / Async

!: , , , $watch, , undefined, async API

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

, , .

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

+1

Source: https://habr.com/ru/post/1664653/


All Articles