我需要在音频标签中的歌曲完成后动态更改一些范围变量。我的问题是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>
答案 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();
};
}
}
});