use*_*387 10 javascript directive input angularjs
我正在尝试使用隔离范围创建一个简单的分页指令.出于某种原因,当我手动更改值时,它有点笨拙.这是我的问题:
当我向前和向后翻页时,效果很好.真棒
当我进入该字段的页面时,它的工作原理.大
但是,如果我进入一个页面到现场,然后尝试去向前和向后的NG-模型似乎打破我进入一个页面到后场.当我没有孤立我的范围时,我有它工作,但我很困惑为什么它会打破它.这是我的代码:
HTML:
<paginate go-to-page="goToPage(page)" total-pages="results.hits.pages" total-hits="results.hits.total"></paginate>
Run Code Online (Sandbox Code Playgroud)
指示:
'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);
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Che*_*try 15
注意ng-if- 它创建了一个新的范围.如果你把它改成ng-show,你的例子就可以了.如果确实要使用ng-if,请创建一个对象来存储范围变量current.也许是这样的scope.state.current?
scope.state = {
current: 1
};
Run Code Online (Sandbox Code Playgroud)
为了避免像这样的混淆,我始终保持我的绑定,something.something而不仅仅是something.
编辑:这里有很好的解释 - http://egghead.io/lessons/angularjs-the-dot
Md *_*him 11
由于javascript的原型层次结构,请在使用ng-model时始终尝试使用模型而不是使用原始类型.
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);
}
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
希望这会解决你的问题:)
有关详细信息,请参阅Understanding-Scopes