如何将 ng-show 与控制器中返回 true/false 的函数一起使用

How to use ng-show with a function in the controller that returns true/false

本文关键字:false 函数 一起 true 返回 ng-show 控制器      更新时间:2023-09-26

我是AngularJS的新手,我在理解ng-show属性的工作时遇到了麻烦。我正在尝试在视频中创建一个模态弹出窗口,该弹出窗口显示视频的当前时间为 7 秒、14 秒或 21 秒。所以我使用 ng-show="dc.timeCheck()",其中"dc"是我的控制器,'timeCheck()' 我在控制器中的函数返回"true"并暂停视频,如果时间是提到的其他时间之一,它返回 false 并播放视频。但是我无法让它工作,尽管浏览了各种文档和教程,但我还是没有看到原因!

我的代码

.HTML:

 <div ng-controller="divCtrl as dc">
        <div id="ui1" ng-show="dc.timeCheck()" >

            <form role="form" ng-submit="submit()">
                <div class="form-group">
                    <h2 style="color:brown;">{{ques[x]}}</h2>
                    <input type="text" class="form-control">
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>
        </div>
        <video id="myVideo" class="video-js vjs-default-skin"
        controls preload="auto" width="640" height="340"
        poster=""data-setup='{"example_option":true}' >
        <source src="blue.mp4" type='video/mp4' ng-controller="vidCtrl as vc" ng-model="started"/>
        </video>
    </div>

JAVASCRIPT:

    var video = videojs('myVideo');
    var timeCheck=function(){
    var currT=Math.floor(video.currentTime());
    if ((currT===7||currT===14||currT===21 )&& currT!=0)
        {   
            video.pause();
            return true;
        }
    else {
        video.play();
        return false;
    }

};

'对于完整代码,粘贴链接是JavaScript: http://pastebin.com/ruY5bhhG网页: http://pastebin.com/sNxK2K4i

'

它不会以这种方式工作,因为一个简单的事实,即没有任何东西在您想要的时间间隔内触发timeCheck()函数。您需要在控制器中使用$timeout,以便它每 7 秒、每秒或您想要的任何时间运行一次。当它运行时,它将更新一个变量,而不是一个函数,你将拥有:

<div id="ui1" ng-show="dc.timeCheck" >
    ...
</div>

对于$timeout部分,您首先需要将$timeout注入控制器,然后在控制器初始化时执行以下操作:

$scope.checkTimeInterval = function () { 
     $scope.timeout = $timeout($scope.checkTimeInterval, 7000); //schedule the next run
     var result = //do your tests
     $scope.timeCheck = result; //this updates the variable that is binded to the ng-show
}
$scope.timeout = $timeout($scope.checkTimeInterval, 7000); //or any other time interval