[英]Angular input inside of directive
我有一个正在使用一些分页控件构建的角度指令。
<div>
<!-- table logic here -->
</div>
<div>
<button bg-click="current=prevPage(current);">Prev</button>
<input ng-model="current" />
/{{pages}}
<button bg-click="current=nextPage(current);">Next</button>
</div>
它工作正常,但是当然可以在input
更改值。
在输入新值之前,它还将在删除过程中拾取空字符串。
current
值更改之前在指令中进行监听。 我也许理解错你的问题。 仅当您在输入之外单击时,这将更新模型
<input ng-model="current" ng-model-options="{updateOn: 'blur'}" />
换句话说,当您更改输入值时,它将调用一个函数,该函数测试新值是否有效并将其设置为当前值。
HTML:
<div>
<button bg-click="current=prevPage(current);">Prev</button>
<input type="number" ng-model="currentInput" ng-change="changeCurrent()" />
/{{pages}}
<button bg-click="current=nextPage(current);">Next</button>
</div>
控制器:
$scope.currentInput = $scope.current;
$scope.changeCurrent = function(){
if ($scope.currentInput!=""){
$scope.current = $scope.currentInput;
}
}
ngModelOptions
在这种情况下很有用。 你可以这样写
<input ng-model="current" ng-model-options="{ updateOn: 'default', debounce: {'default': 500, 'blur': 0} }" />
将更新值延迟为默认值500ms,并在失去焦点时立即更新。
该问题也已被回答了几次 ,因此您应该能够在其他问题中找到更多信息。
更新:
$scope.$watch(
function() {
return $scope.current;
}, function(oldVal, newVal) {
if (!newVal) {
$scope.current = oldVal
}
}
);
如果oldVal
还是null或空字符串,则只要newVal有值,就可以将$scope.current
复制到另一个作用域变量(例如$scope.savedCurrent
),如果没有, $scope.current
其复制回到$scope.current
。
您可以在分页之前检查可变current
的值。
我假设您正在使用$watch()
来监听变量current
的变化。
指令链接中的代码,
scope.$watch("current", function(newVal, oldVal){
if(angular.isNumber(newVal)){
// your variable is a number
// Do your pagination here
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.