如何在角度中创建自动生成ID?

时间:2017-02-10 12:34:34

标签: angularjs

  

想要在刷新页面的角度输入框中创建自动生成代码   像在php中的rand(函数)。我正在使用这个脚本。但问题   它在页面刷新时消失得不能正常工作。

    <script type="text/javascript">
    function randString(x){
    var s = "OL-";
    while(s.length<x&&x>0){
        var r = Math.random();
        s+= (r<0.1?Math.floor(r*100):String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65)));
    }
    return s;
}
document.getElementById("referal_code").value = randString(10);
</script>

<input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>

4 个答案:

答案 0 :(得分:0)

试试这个

 <script type="text/javascript">


function getNewID() {
            try {
                var myDate = new Date();
                var varID = $scope.coID + "" + myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds();
                if (varID.Length > 15) {
                    varID = varID.substr(0, 15);
                }
                return varID;
            } catch (e) {
                console.log(e.message);
            }
        }

    function randString(x){
    var s = "OL-";
    while(s.length<x&&x>0){
        var s = getNewID();
    }
    return s;
}
document.getElementById("referal_code").value = randString(10);
</script>

答案 1 :(得分:0)

对于角度世界中的任何属性,您可以使用如下插值:

<input id="{{randString(10)}}"/>

答案 2 :(得分:0)

如果您希望将某个值作为id并且在刷新后不会丢失,则必须将其保存在某个Web存储(localstorage,sessionstorage)上。

e.g。 :

function randString(x){
 // ... your function's logic

 //Save it in localStorage before returning it
 localStorage.inputId = s;

 return s;
}

document.getElementById("referal_code").value = localStorage.inputId || randString(10)

答案 3 :(得分:0)

试试这个

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">


        function getNewID() {
            try {
                var myDate = new Date();
                var varID = myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds();
                if (varID.Length > 15) {
                    varID = varID.substr(0, 15);
                }
                return varID;
            } catch (e) {
                console.log(e.message);
            }
        }

        function randString(x){
            var s = getNewID();
            return s;
        }
        window.onload = function(){
            document.getElementById("referal_code").value = randString(10);
        }
    </script>
</head>
<body>
    <input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>
</body>
</html>