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" />
-
-
- <input type="number" ng-model="value2" string-to-number/>
- body>
- html>