我正在尝试自动更新我正在播放的歌曲并将其显示在我的网站上。为此,我使用了$ interval函数。问题是模型(div)每10秒刷新一次,而我只希望在歌曲改变时刷新(并每10秒检查一次)
我尝试通过setInterval()更改$ interval函数,但是没有运气。
angular.module('lastfm-nowplaying', [])
.directive('lastfmnowplaying', ['uiCreation', 'lastFmAPI', 'lastFmParser', '$interval', function(uiCreation, lastFmAPI, lastFmParser, $interval){
var link = function(scope, element, attrs){
scope.$watch('config', function(value) {
load();
});
var load = function(){
function SongCheck(){
var latestTrack;
if (scope.config){
if (scope.config.apiKey){
lastFmAPI.getLatestScrobbles(scope.config)
.then(function(data){
latestTrack = lastFmParser.getLatestTrack(data);
angular.element(element).addClass('lastfm-nowplaying');
uiCreation.create(element[0], scope.config.containerClass, latestTrack);
}, function(reason) {
//Last.fm failure
});
}
else{
var latestTrack = {
title: scope.config.title,
artist: scope.config.artist,
largeImgUrl: scope.config.imgUrl,
xLargeImgUrl: scope.config.backgroundImgUrl,
}
angular.element(element).addClass('lastfm-nowplaying');
uiCreation.create(element[0], scope.config.containerClass, latestTrack);
}
}
}
SongCheck();
$interval(function () {
SongCheck();
} , 8000);
}
};
return {
scope:{
config: '=config'
},
link: link
};
}])
代码有效,但是我希望模型在检测到更改(在这种情况下为json文件)时更改。
答案 0 :(得分:1)
删除$interval
计时器并使用监视程序的“深度监视”版本:
scope.$watch('config', function(value) {
load(value);
̶}̶)̶;̶
}, true);
通常,观察者仅在对象 reference 更改时才会触发。将第二个参数设置为true
,以使观察者在对象内容更改时触发。
有关更多信息,请参见