Angular 指令作用域变量未定义。

4

我正在尝试在link中访问我的作用域变量,但它们显示为未定义

/** @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

我尝试使用@而不是=,并且更改了绑定以使用{{}},但仍未定义。我可以使用$observe,但我想一次获取多个属性的值以进行一些计算。有什么最好的方法吗? HTML代码
 <table-pagination
    current-page="$ctrl.tableMeta.currentPage"
    total-count="$ctrl.tableMeta.totalCount"
    total-pages="$ctrl.tableMeta.totalPages"
    per-page="$ctrl.tableMeta.perPage"></table-pagination>

更新: 我想这可能是因为指令没有从 API/异步获取的$ctrl.tableMeta中获取更新的值。

解决方案!: 哦,我发现我的错误在于我需要使用$watch,否则它会得到旧值,而默认情况下未定义,因为它尚未由API异步设置。

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

2
请提供您使用指令时的HTML。 - Curiousdev
currentPage 需要从 HTML 中传递! - Dhaval Marthak
你能分享一下你的tablePagination.html文件吗? - Suresh B
@Curiousdev,添加了HTML。 - Jiew Meng
@SureshB 添加了 HTML。 - Jiew Meng
1个回答

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>

{{链接1:plunker}}


我发现这个代码可以工作,但是一旦我使用一个动态属性current-page=$ctrl.tableMeta.currentPage,它就会出问题。我认为指令没有在API设置currentPage时获取到它的值? - Jiew Meng
好的,我发现我需要使用$watch - Jiew Meng
很棒 @JiewMeng - MMK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接