我正在尝试访问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>
更新:我想知道是否因为该指令未从$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)
})
答案 0 :(得分: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>