user6934713 user6934713 - 1 month ago 11
AngularJS Question

Angular ng-show doesnt work from the controller

I am trying to display a div after a video finishes. The alert shows up after the video finish but the div is still not visible.What am I doing wrong.
Thank you for the help in advance.

@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>


This is the controller

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");
}


});

Answer

It looks like that you need to force digest in order to reflect scope changes in the view. This happens because you are changing the scope value using a javascript event.

In your controller add $timeout:

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

In your function wrap the code with it:

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