user6934713
user6934713

Reputation:

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

});

Upvotes: 1

Views: 142

Answers (2)

Lee Brindley
Lee Brindley

Reputation: 6482

As stated in the comments, it's best practice to bind to an object property. Try the following:

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

As the comments state, I've added an extra property to the object, if you paste the code above you should see "Hello World" inside the <p> element. I placed this in the answer as your question does not provide all of the relevant code.

Upvotes: 1

Sarantis Tofas
Sarantis Tofas

Reputation: 5167

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

Upvotes: 1

Related Questions