I want make a function in AngularJS to replace all values on a page but I am getting an error.
我想在AngularJS中创建一个函数来替换页面上的所有值,但是我得到了一个错误。
Here is the HTML:
HTML:
<input type="text" ng-keyup="number_only(num_page)" ng-model="num_page"/>
<input type="text" ng-keyup="number_only(num_book)" ng-model="num_book"/>
<input type="text" ng-keyup="number_only(price)" ng-model="price"/>
and here is my script:
这是我的脚本:
$scope.number_only= function(num_page){
return $scope.num_page = num_page.replace(/[^0-9]/g, '');
}
1 个解决方案
#1
1
In your code the num_page always updates irrespective of the model.
在您的代码中,num_page总是在不考虑模型的情况下进行更新。
You can assign the value of model to ng-keyup directly to work as expected.
您可以直接将模型的值分配给ng-keyup,以便按照预期工作。
Here is the working example.
这里是一个工作示例。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.num_page = null;
$scope.num_book = null;
$scope.price = null;
$scope.number_only= function(num_page){
return num_page.replace(/[^0-9]/g, '');
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Number of Page<input type="text" ng-keyup="num_page=number_only(num_page)" ng-model="num_page"/><br>
Number Of Book<input type="text" ng-keyup="num_book=number_only(num_book)" ng-model="num_book"/><br>
Price<input type="text" ng-keyup="price=number_only(price)" ng-model="price"/>
<br>
Number of Page: {{num_page}}
Number of Book: {{num_book}}
Price: {{price}}
</div>
</body>
</html>
#1
1
In your code the num_page always updates irrespective of the model.
在您的代码中,num_page总是在不考虑模型的情况下进行更新。
You can assign the value of model to ng-keyup directly to work as expected.
您可以直接将模型的值分配给ng-keyup,以便按照预期工作。
Here is the working example.
这里是一个工作示例。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.num_page = null;
$scope.num_book = null;
$scope.price = null;
$scope.number_only= function(num_page){
return num_page.replace(/[^0-9]/g, '');
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Number of Page<input type="text" ng-keyup="num_page=number_only(num_page)" ng-model="num_page"/><br>
Number Of Book<input type="text" ng-keyup="num_book=number_only(num_book)" ng-model="num_book"/><br>
Price<input type="text" ng-keyup="price=number_only(price)" ng-model="price"/>
<br>
Number of Page: {{num_page}}
Number of Book: {{num_book}}
Price: {{price}}
</div>
</body>
</html>