javascript - 如何在指令中调用函数

标签 javascript angularjs

从另一个模块调用变量

我有一个播放器,可以显示当前或最新播放的歌曲。现在为了保持内容更新。我用过$interval$scope.$watch注册正在播放的歌曲,该歌曲显示在开发者控制台中。

现在,每当检测到歌曲名发生变化时我想触发 variable "link"它将触发 load()函数(这本质上是需要触发的函数)。然而,varbiale 位于不同的模块中。 我该如何调用它?

我对 AngularJS 不太熟悉,无法真正编辑代码,但我设法获取更新的歌曲信息,并使用 if 语句进行 alang,因此只有在两个函数之间检测到更改时才会触发 CurrentSongLatestSong

angular.module('app', ['lastfm-nowplaying'])
    .controller('mainCtrl', ['$scope', '$http', '$interval', function ($scope, $http, $interval) {

        $scope.lastFmConfig = {
            apiKey: 'API',
            user: 'USER',
            containerClass: 'content'
        };

        $scope.$watch('currentsongs', function (CurrentSong, LatestSong) {
            if (CurrentSong != LatestSong) {
                console.log("Change detected");
                console.log($scope.songdata);
            }

        }, true);
        var checkData = function (songcheck) {
            $http({
                method: 'GET',
                url: 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=USER&api_key=API&format=json&limit=1'
            }).then(function (songdata) {
                $scope.songdata = songdata;
                $scope.currentsongs = songdata.data.recenttracks.track[0].name;
                console.log($scope.currentsongs);
            }, function (error) {
                //oopsie
            });
        };
        checkData();
        $interval(function () {
            checkData();
        }, 10000);


  }]);
angular.module('lastfm-nowplaying', [])
    .directive('lastfmnowplaying', ['uiCreation', 'lastFmAPI', 'lastFmParser', function (uiCreation, lastFmAPI, lastFmParser) {
        var link = function (scope, element, attrs) {
            scope.$watch('config', function (value) {
                load();
            });

            var load = function () {....

最佳答案

我终于明白了! 通过反复试验,我成功解决了这个问题。

解决方案实际上非常简单,因为我知道我已经很接近了。

$scope.lastFmConfig = {
            apiKey: 'API',
            user: 'USER',
            containerClass: 'content'
        };

        $scope.$watch('currentsongs', function (CurrentSong, LatestSong) {
            if (CurrentSong != LatestSong) {
                console.log("Change detected");
                console.log($scope.songdata);
                $scope.lastFmConfig = {
            apiKey: 'API',
            user: 'USER',
            containerClass: 'content'
        };
            }

一旦检测到更改,我就再次运行lastFmConfig。

希望它可以帮助别人。

关于javascript - 如何在指令中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57379738/

相关文章:

javascript - xhtml 验证 javascript

php - 使用 cURL POST 方法的问题

javascript - 通常无法在 iPhone 上锁定横向方向

javascript - Jasmine spy 调用的问题

javascript - AngularJS + Typescript => Controller 范围

javascript - 生成随机整数

javascript - 在 javascript 中迭代数组并将其连接到另一个变量

javascript - Angular ng-repeat 反向

javascript - Angularjs 中 View 之间的平移动画

html - AngularJS HTML5 嵌套路由