我正在尝试使用隔离范围创建一个简单的分页指令。出于某种原因,当我手动更改值时,它有点笨拙。这是我的问题:
当我向前和向后翻页时,效果很好。真棒
当我进入该字段的页面时,它可以工作。大
但是,如果我在该字段中输入一个页面,然后尝试前进和后退,那么在我进入该字段后,ng-model似乎会中断。当我没有孤立我的范围时,我有它工作,但我很困惑为什么它会打破它。这是我的代码:
HTML:
<paginate go-to-page="goToPage(page)" total-pages="results.hits.pages" total-hits="results.hits.total"></paginate>
指令:
'use strict';
angular.module('facet.directives')
.directive('paginate', function(){
return {
restrict: 'E',
template: '<div class="pull-right" ng-if="(totalPages !== undefined) && (totalPages > 0)">'+
'<span class="left-caret hoverable" ng-click="changePage(current-1)" ng-show="current > 1"></span> Page'+
' <input type="number" ng-model="current" class="pagination-input" ng-keypress="enterPage($event)"/> of'+
' {{totalPages}} '+
'<span class="right-caret hoverable" ng-click="changePage(current+1)" ng-show="current < totalPages"></span>'+
'</div>',
scope: {
goToPage: '&',
totalPages: '=',
totalHits: '='
},
link: function(scope) {
scope.current = 1;
scope.changePage = function(page) {
scope.current = page;
window.scrollTo(0,0);
scope.goToPage({page:page});
};
scope.enterPage = function(event) {
if(event.keyCode == 13) {
scope.changePage(scope.current);
}
}
}
}
});
我做错了什么?
答案 0 :(得分:15)
小心ng-if
- 它会创建一个新的范围。如果你把它改成ng-show,你的例子就可以了。如果您确实想使用ng-if
,请创建一个对象来存储范围变量current
。也许像scope.state.current
?
scope.state = {
current: 1
};
为避免这样的混淆,我始终将绑定设为something.something
,而不仅仅是something
。
编辑:这里有很好的解释 - http://egghead.io/lessons/angularjs-the-dot
答案 1 :(得分:11)
由于javascript的原型层次结构,请始终尝试使用模型而不是使用基本类型,因为javascript的原型层次结构。
angular.module('facet.directives').directive('paginate', function () {
return {
restrict: 'E',
replace: true,
template: '<div class="pull-right discovery-pagination" ng-if="(totalPages !== undefined) && (totalPages > 0)">' +
'<span class="left-caret hoverable" ng-click="changePage(current-1)" ng-show="current > 1"></span> Page' +
' <input type="number" ng-model="current.paging" class="pagination-input" ng-keypress="enterPage($event)"/> of' +
' {{totalPages}} ' +
'<span class="right-caret hoverable" ng-click="changePage(current+1)" ng-show="current < totalPages"></span>' +
'</div>',
scope: {
goToPage: '&',
totalPages: '=',
totalHits: '='
},
link: function(scope) {
scope.current = {paging:1};
scope.changePage = function(page) {
scope.current.paging = page;
window.scrollTo(0, 0);
scope.goToPage({ page: page });
};
scope.enterPage = function(event) {
if (event.keyCode == 13) {
scope.changePage(scope.current.paging);
}
};
}
};
});
希望这能解决您的问题:)
有关详情,请仔细阅读Understanding-Scopes