Angular. js Implementation of Chinese Character Conversion Example Code

  • 2021-07-02 23:33:03
  • OfStack

Introduction to AngularJS

AngularJS is an JavaScript framework. It can pass through < script > Tag is added to the HTML page.

AngularJS extends HTML through instructions and binds data to HTML through expressions.

The following is an example code of Angular. js to realize digital conversion of Chinese characters. The specific code is as follows:


// 1、实现输入数字输出对应汉字,要求使用angularjs,不准使用$watch函数,for循环;提示:ng-change指令
<div ng-app="myApp" ng-controller="changeCtrl"> // 定义1个app指令 定义1个controller 指令用于为你的应用添加控制器。在控制器中,你可以编写代码,制作函数和变量,并使用 scope 对象来访问。
数字: <input ng-model="number" ng-change="changeFunc(number)"> // ng-model 指令绑定了 HTML 表单元素到 scope 变量中。 如果 scope 中不存在变量, 将会创建它。 ng-change 事件在值的每次改变时触发
<h1>你输入了: {{result}}</h1> // 和ng-model数据绑定的值
</div>
<script>
var app = angular.module('myApp', []); // 新建1个模块,注意新的模块需要在 app.js 里面引入
app.controller('changeCtrl', function($scope) { // 建立controller方法 供html使用
$scope.number = ""; // 这里是input框中出现的值
$scope.result = ""; // 结果是h1中出现的值
var array=["零","1","2","3","4","5","6","7","8","9","10"];
$scope.changeFunc=function(number){ // 定义1个ng-change方法,当input内的值改变时出发(input内输入1个值,方法改变1次)
console.log("number=",number);
if(number != ''){ 
$scope.result = "";
var atr=number.replace(/(.)(?=[^$])/g,"$1,").split(",");//第1种 // 通过截取的形式每1个数字添加‘,'split把字符串变成数组 
atr.forEach(function(e){ // 循环数组atr
$scope.result += array[e];
});
/*for(var a in number){ //第2种 
console.log("number[a]=",number[a]);
var i = parseInt(number[a]);
$scope.result += array[i];
}*/
}
};
});
</script>

Related articles: