2016-12-23 156 views
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> 

更新:不知从$ctrl.tableMeta它,因为指令没有得到更新值是从API来/异步

解决方案!:哦,我发现我错了,我需要使用$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

+0

'currentPage'需要从HTML传递! –

+0

你可以分享你的tablePagination.html吗? –

回答

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

+0

我发现这个方法可行,但是一旦我使用了一个动态属性'current-page = $ ctrl.tableMeta.currentPage'。我认为这个指令在获取API设置的时候没有获得currentPage的值? –

+0

好吧,我发现我需要使用'$ watch' –

+0

大@JiewMeng – MMK