angularjs select number type default value required validate

前端之家收集整理的这篇文章主要介绍了angularjs select number type default value required validate前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div ng-app="app" ng-controller="controller">
        <form name="form" novalidate>
            <div class="form-group" ng-class="{ 'has-error': form.value.$invalid }">
                <label for="exampleInputEmail1">select</label>
                <!--http://stackoverflow.com/questions/32304519/ng-pattern-regex-to-allow-all-characters-except-decimal-value-->
                <select class="form-control" ng-model="item.value" name="value" convert-to-number ng-pattern="/^(?!0$).*/" required>
                    <option value="0" disabled>please choose a number</option>
                    <option ng-repeat="option in [1,2,3,4,5]" value="{{option}}">{{option}}</option>
                </select>
                <span ng-show="form.value.$error.required" class="err-msg">required</span>
                <span ng-show="form.value.$error.pattern" class="err-msg">pattern</span>
            </div>
            <button type="button" class="btn btn-default" ng-click="submit(form)">submit</button>
        </form>
    </div>
    <script src="http://cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script>
    <script>
        'use strict';

        var app = angular.module('app',[])

        app.controller('controller',function ($scope) {
            $scope.item = {
                value: 0,}
            $scope.submit = function (form) {
                if (!form.$valid) {
                    return
                }
                alert(JSON.stringify($scope.item))
            }
        })

        //http://stackoverflow.com/a/35407627/2586541
        app.directive('convertToNumber',function () {
            return {
                require: 'ngModel',link: function (scope,element,attrs,ngModel) {
                    //value
                    ngModel.$parsers.push(function (val) {
                        //return '' + val;
                        return parseInt(val,10);
                    });
                    //show
                    ngModel.$formatters.push(function (val) {
                        //return parseInt(val,10);
                        return '' + parseInt(val || 0,10);
                    });
                }
            };
        });
    </script>
</body>
</html>
原文链接:https://www.f2er.com/angularjs/149275.html

猜你在找的Angularjs相关文章