Home How to replace a string globally in AngularJS?
Reply: 1

How to replace a string globally in AngularJS?

koe
1#
koe Published in 2018-02-14 04:47:39Z

I want make a function in AngularJS to replace all values on a page but I am getting an error.

Here is the 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, '');
}
Unknown
2#
Unknown Reply to 2018-02-14 05:27:42Z

In your code the num_page always updates irrespective of the model.

You can assign the value of model to ng-keyup directly to work as expected.

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>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.772086 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO