[英]AngularJS input ng-model not updating
我正在嘗試使用隔離范圍創建一個簡單的分頁指令。 出於某種原因,當我手動更改值時,它有點笨拙。 這是我的問題:
當我向前和向后翻頁時,效果很好。 真棒
當我進入該領域的頁面時,它的工作原理。 大
但是,如果我在該字段中輸入一個頁面然后嘗試前進和后退,那么在我進入該字段后,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);
}
}
}
}
});
我究竟做錯了什么?
注意ng-if
- 它會創建一個新的范圍。 如果你把它改成ng-show,你的例子就可以了。 如果您確實想使用ng-if
,請創建一個對象來存儲范圍變量current
。 也許像scope.state.current
這樣的scope.state.current
?
scope.state = {
current: 1
};
為了避免像這樣的混淆,我總是將綁定視為something.something
而不僅僅是something
。
編輯:這里有很好的解釋 - http://egghead.io/lessons/angularjs-the-dot
由於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);
}
};
}
};
});
希望這會解決你的問題:)
有關詳細信息,請參閱Understanding-Scopes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.