仅在角度模板内生成一次随机 ID 号

sky*_*ker 2 javascript angularjs

我想知道页面加载后在角度模板中生成随机 id 的方法。我面临的问题是,每一秒我都会在两个跨度中获得不同的 ID。我希望它在两个地方都相同,并且不希望它每秒都改变其值。这是我的简单模板:

<main class="has-header has-padding">
<div id = "command">-ID:<span>{{vm.getRandomId()}}</span> -connect  -run</div>
    <hr>
<div id = "command">-ID:{{vm.getRandomId()}}</div>
Run Code Online (Sandbox Code Playgroud)

我的控制器:

'use strict';

(function() {
    angular
        .module('myApp')
        .controller('myController.ctrl', myController);

    myController.$inject = ['$scope'];

    function screenSharingCtrl($scope) {
        angular.extend(this, {
            getRandomId:getRandomId
        });

        function getRandomId() {
            return Math.floor((Math.random()*6)+1);
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

抱歉,如果这是一个重复的问题。任何帮助表示赞赏!谢谢你!

小智 6

只需将绑定更改为

{{ vm.id }}
Run Code Online (Sandbox Code Playgroud)

和你的视图模型

function screenSharingCtrl($scope) {

        function getRandomId() {
            return Math.floor((Math.random()*6)+1);
        }

        this.id = (typeof this.id === 'undefined') ? getRandomId() : this.id; 
    }
Run Code Online (Sandbox Code Playgroud)