在Angular中如何将输入内容更改为另一种格式,然后显示该格式

时间:2017-11-04 12:51:31

标签: javascript html angularjs

W3CSchool的最初实践 - Angular Service。我想通过将HTML输入中的内容转换为HTML元素中的十六进制来推进该实践。怎么做?提前谢谢。

原始版本:

<!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">
<p>The hexadecimal value of 255 is:</p>
<h1>{{hex}}</h1>
</div>
<!--A custom service with a method that converts a given number into a hexadecimal number.-->

<script>//angular
var app = angular.module('myApp', []); //create module

app.service('hexafy', function() {   //create a custom service
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {  //create a controller
  $scope.hex = hexafy.myFunc(255);
});
</script>

</body>
</html>

我的高级版本(但失败了):

<!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">

<p>The hexadecimal value of 255 is:</p>
<input type="text" ng-model="hexInput"/>
<h1>{{hexInput}}</h1>   <!--get the value in the input-->
<h1>{{hex}}</h1>   
</div><!--A custom service with a method that converts a input number into a hexadecimal number.-->
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc($scope.hexInput);
});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

以下是工作解决方案:

您需要订阅输入更改以在每次输入内容时计算值,而不是仅在控制器初始化时计算一次。我们通过ng-change='calculateHex()'执行此操作。

每次计算时都需要检查空字符串,如果没有十六进制计算则返回空白字符串。

这里的最后一点是你应该先将x解析为数字,因为它来自ng-model的字符串。然后再次.toString()

<!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">

<p>Input number</p>
<input type="text" ng-model="hexInput" ng-change="calculateHex()"/>
<h1>The hexadecimal value is: <span style="text-transform: uppercase">{{hex}}</span></h1>   
</div><!--A custom service with a method that converts a input number into a hexadecimal number.-->
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return parseInt(x, 10).toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
      $scope.calculateHex = function() {
         $scope.hex = $scope.hexInput && $scope.hexInput.length && hexafy.myFunc($scope.hexInput) || '';
      }
});
</script>
</body>
</html>