angularjs directive(指令用法)将int转化成string

1)将int转化成string

a)angularjs select在ng-model值为int的时候无法实现双向绑定

b)通过directive(指令用法)将int转化成string就能实现双向绑定

<!DOCTYPE html>
<html ng-app="my_app">
	<head>
		<script src="angular.min.js"></script>
		<script type="text/javascript">
			var app = angular.module("my_app", []);
			app.controller('my_controller', function($scope) {
				$scope.type = 2;
				$scope.typeList = [{
					code: 1,
					name: '分期付款'
				}, {
					code: 2,
					name: '一次性付款'
				}];
			}).directive("toString", function() {
				return {
					restrict: "A",
					require: "ngModel",
					link: function(scope, elem, attr, ngModelCtr) {
						ngModelCtr.$formatters.push(function(viewValue) {
							if (typeof viewValue != "undefined") {
								return viewValue.toString();
							}
						})
					}
				}
			});
		</script>
	</head>
	<body ng-controller="my_controller">
		<select ng-model="type" to-String>
			<option ng-repeat="item in typeList" value="{{item.code}}">
				{{item.name}}
			</option>
		</select>
	</body>
</html>

2)将string转化成int

a)angularjs input=number在ng-model值为string的时候无法实现双向绑定

b)通过directive(指令用法)将string转化成int就能实现双向绑定

<!DOCTYPE html>
<html ng-app="my_app">
	<head>
		<script src="angular.min.js"></script>
		<script type="text/javascript">
			var app = angular.module("my_app", []);
			app.controller('my_controller', function($scope) {
				// 绑定值是数字
				$scope.value1 = 1.1;
				// 绑定值是字符串
				$scope.value2 = '2.2';
			}).directive('stringToNumber', function() {
				return {
					require: 'ngModel',
					link: function(scope, element, attrs, ngModel) {
						ngModel.$parsers.push(function(value) {
							return '' + value;
						});
						ngModel.$formatters.push(function(value) {
							if (value)
								return Number(value);
							return value;
						});
					}
				};
			});
		</script>
	</head>
	<body ng-controller="my_controller">
		<input type="number" ng-model="value1" />
		<!-- 因为type=number绑定的是数字 -->
		<!-- 通过指令用法将字符串转化成number实现双向绑定 -->
		<input type="number" ng-model="value2" string-to-number/>
	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值