javascript - $watch 没有读取对象
问题描述
在我的网站上有一个播放器,它显示我当前列出的歌曲。但是,为了更新显示的歌曲,我不得不刷新页面。
至于现在,我希望代码检查外部 json 文件。它应该检查歌曲名称,当检测到更改时,它应该更新网站上的播放器。
不幸的是,我在这里遇到了障碍。
首先我尝试使用该$interval
功能,虽然这确实有效,但它会<div>
像刷新页面一样刷新。
我尝试了该scope.$watch
功能,但它似乎不起作用。看起来 $watch 只在页面加载时触发一次。这可能是由于范围不是侦听器。但是,当我尝试添加侦听器时,我需要更改模块,因为它是一个指令......
angular.module('lastfm-nowplaying', [])
.directive('lastfmnowplaying', ['uiCreation', 'lastFmAPI', 'lastFmParser', '$http', function (uiCreation, lastFmAPI, lastFmParser, $http) {
var link = function (scope, element, attrs) {
$http({
method: 'GET',
url: 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=--NAME--&api_key=--API--&format=json&limit=1'
}).then(function (songdata) {
var currentsongs = songdata.data.recenttracks.track[0].name;
console.log(songdata);
console.log(currentsongs);
}, function (error) {
//oopsie
});
scope.$watch('currentsongs', function (value) {
load(value);
console.log("Change detected");
}, true);
var load = function () {
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);
}
}
}
};
return {
scope: {
config: '=config'
},
link: link
};
}])
HTML
<body ng-app="app" ng-controller="mainCtrl">
<div lastfmnowplaying config="lastFmConfig"></div>
</body>
因此,通过控制台我可以调用 json 文件并获取歌曲的名称,但我无法使用 更新播放器scope.$watch
,它只会触发一次(?)
我只知道 Angular 的基础知识,因此我无法很快自己解决这个问题。
解决方案
这是一个每 6 秒轮询一次 API 的主控制器:
app.controller("mainCtrl", function($scope, $interval, service) {
service.getLastTrack.then(function (track) {
$scope.latestTrack = track;
});
$interval(getNextTrack, 6000);
function getNextTrack() {
service.getLastTrack.then(function (track) {
if ($scope.latestTrack.name != track.name) {
$scope.latestTrack = track;
};
});
}
})
用法:
<body ng-app="app" ng-controller="mainCtrl">
<div lastfmnowplaying config="latestTrack"></div>
</body>
这是一个如何在数据的 a 属性更改时轮询 API 并更新指令配置的示例。
有关详细信息,请参阅
推荐阅读
- ffmpeg - ffmpeg 视频裁剪“无法将选项值”“解析为布尔值”
- reporting-services - 如何在 SSRS 中显示条形图的空组?
- c# - SQL Server Express 的连接字符串仅适用于同一服务器,但不适用于其他客户端
- python - 以前导入的模块是否仍然可以“记住”?
- reactjs - Jest/Enzyme - 动作必须是普通对象。使用自定义中间件进行异步操作
- python - 需要将 JSON 字符串加载到 DataFrame 中
- pact - 如何运行 PACT Broker can-i-deploy 脚本?
- java - Selenium - 无法在 Firefox 中将父窗口重新聚焦
- javascript - For循环覆盖对象
- php - Composer 需要带有类似 OR 运算符的块