2

I need to dynamically change some scope variables after song in audio tag is finished. My problem is that scope.test is not affected by audio directive.

angular.module('playItApp', [])

    .controller('audioController', ['$scope', function($scope){
        $scope.test = 'songNotFinished';
    })

    .directive('audio', function(){
        return {
            restrict: 'E',
            link: function(scope, element, attrs){
                element[0].onended = function() {
                    scope.test = 'songFinished';
                    this.load();
                };
            }
        }
    });


<div ng-controller="audioController">
    <h1>{{ test }}</h1>
    <audio controls autoplay>
        <source ng-src="{{ some_path }}" type="audio/mpeg">
    </audio>
</div>

1 Answer 1

3

You just need tell the directive which part of the scope needs two-way binding. Which means it binds from your parent scope, and also communicate back to your controller that something in the scope has changed with scope.$apply(function () { /* what's changing */ });

.directive('audio', function(){
    return {
        restrict: 'E',

        scope: {
            'test' : '=' // Two-way binding <--

            // There are three options here when you're dealing with scope
            //    @ --> Attribute string binding
            //    & --> Callback method binding
            //    = --> Two-way model binding
        },

        link: function(scope, element, attrs){
            element[0].onended = function() {

                // Make sure to call an anonymous function inside of .$apply
                scope.$apply(function () { 
                    scope.test = 'songFinished';
                });

                this.load();
            };
        }
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Actually problem was more complicated, I needed scope.$apply(); at the end of link function in directive.
@user3575996 Added the scope.$apply(function () {}); almost forgot you need to communicate back to the controller!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.