在Angular指令中更改事件处理程序的范围

时间:2015-03-19 18:08:42

标签: angularjs

我需要在音频标签中的歌曲完成后动态更改一些范围变量。我的问题是scope.test不受audio指令的影响。

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 个答案:

答案 0 :(得分:3)

您只需告诉指令范围的哪一部分需要双向绑定。这意味着它会与您的父作用域绑定,并且还会通过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();
            };
        }
    }
});