Angular ng-show无法从控制器中运行

时间:2016-10-19 15:15:32

标签: javascript angularjs

我想在视频播放完毕后显示div。视频完成后警报显示,但div仍然不可见。我做错了什么。 感谢您的帮助。

@section scripts
{
    <script type="text/javascript" src="~/App/Controllers/TestController.js"></script>
}
<div ng-controller="TestController as ctrl" class="md-content" ng-cloak>
    <h1>Test</h1>

    <video id="myVideo"  controls autoplay>
        <source src="~/Videos/Test1.mp4">
    </video>

    <div id="test" ng-show="ui.showTest">
        <h1>Test</h1>
        Added this as a test to see if your controller is linked to the view
        <p>{{ui.shouldSeeThis}}</p>
    </div>
</div>

这是控制器

angular.module('MyApp', ['ngMaterial', 'ngMessages'])
.controller('TestController', function ($scope, $http, $filter, $mdDialog) {


var vid;

function initializePlayer() {

    vid = document.getElementById("myVideo");
    vid.addEventListener('ended', videoFinish, false);
}

window.onload = initializePlayer;

$scope.ui = {
    showTest: false,
    //I've added this to see if your controller is linked to the view
    shouldSeeThis: "Hello World"
};
function videoFinish() {
    $scope.ui.showTest = true;
    alert("VideoFinish");
}

});

2 个答案:

答案 0 :(得分:1)

如评论中所述,最佳做法是绑定到对象属性。请尝试以下方法:

<div id="test" ng-show="ui.showTest">
    <h1>Test</h1>
    <!-- Added this as a test to see if your controller is linked to the view-->
    <p>{{ui.shouldSeeThis}}</p>
</div>
$scope.ui = {
    showTest: false,
    //I've added this to see if your controller is linked to the view
    shouldSeeThis: "Hello World"
};
function videoFinish()
{
    $scope.ui.showTest = true;
    alert("VideoFinish");
}

正如评论所述,我为对象添加了一个额外的属性,如果你粘贴上面的代码,你应该在<p>元素中看到“Hello World”。我把它放在答案中,因为你的问题没有提供所有相关的代码。

答案 1 :(得分:1)

看起来您需要强制摘要才能反映视图中的范围更改。这是因为您正在使用javascript事件更改范围值。

在您的控制器中添加$timeout

.controller('TestController', function ($scope, $http, $filter, $mdDialog, $timeout)

在你的函数中用它包装代码:

function videoFinish() {
    $timeout(function() {
      $scope.ui.showTest = true;
      alert("VideoFinish");
    });
}