如果 ng-model 为空,我想为其赋值。我已将默认值分配给来自 Controller 的 ng-model 输入,但是当用户进行更改以删除该值并使输入为空时,我想将默认值分配给 ng-model。
例如。
Controller :
App.controller('mainController',['$scope', function($scope) {
$scope.assignOne= 16;
}]);
查看:
<input ng-model="assignOne" ng-change="changeMe()"/>
现在,输入值变为16。
如果用户进行更改并手动删除此值 16,那么我需要默认值 1,而不是 changeMe() 函数中的空字符串。
注意: 我可以检查空的 ng-model 并覆盖 Controller 中 ng-model 的值。但是,有没有更好的方法来使用 Angular 提供的东西。
我刚刚接触 AngularJS。
最佳答案
按如下方式尝试$watch
$scope.$watch(
"assignOne",
function handleChange( newValue, oldValue ) {
console.log( "assignOne:", newValue );
if(newValue == '') {
newValue = 16;
}
}
);
关于javascript - 如果 ng-model 为空,如何为其赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434299/