我试图在链接中访问我的范围变量,但它们看起来未定义
/** @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>
更新:我想知道它是否因为该指令没有从$ctrl.tableMeta获取来自API / Async的更新值
解决方案!:哦,我发现我的错误是我需要使用$watch,否则它会获得默认未定义的旧值,因为它尚未通过API设置为异步
scope.$watch('currentPage', () => {
scope.start = (scope.currentPage - 1) * scope.perPage + 1
scope.end = Math.min(scope.currentPage * scope.perPage, scope.totalCount)
})
最佳答案 它只是一个例子,我希望它能清除一些事情.
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>