使用参数从角度控制器启动一个函数

时间:2017-05-07 12:41:38

标签: javascript angularjs promise

我需要启动一个需要json的参数的函数, 请求是:

app.controller('getDataCtrl', function ($scope, $http, $ionicLoading) {

$http({
    method: "POST",
    url: "http://someurl/GetPlaylist",
    dataType: "json",
    contentType: "application/json; charset=utf-8"
}).then(function mySucces(response) {

    $scope.allTracks = response.data;
    $scope.recentTracks = response.data.Tracks;
//now i want to luanch the function below that written in a different js file
//and pass parameters
        **startCration(recentTracks[0].Song, recentTracks[0].Artist);**

}, function myError(response) {
    $scope.allTracks = response.statusText;
});
});

这是我需要启动的功能

function startCration(song, artist) {

    MusicControls.create({
        track: song,        
        artist: artist,                           
    }, onCreateSuccess, onCreateError);

但是我似乎无法在成功之后调用该函数

2 个答案:

答案 0 :(得分:2)

当您将所有曲目分配到$scope.recentTracks时,您应该引用$scope.recentTracks而不是recentTracks

startCration(recentTracks[0].Song, recentTracks[0].Artist);

应该是

startCration($scope.recentTracks[0].Song, $scope.recentTracks[0].Artist);

答案 1 :(得分:1)

您基本上可以成功播放活动。这是更新后的代码:

app.controller('getDataCtrl', function ($scope, $http, $ionicLoading,$rootScope) {

$http({
    method: "POST",
    url: "http://someurl/GetPlaylist",
    dataType: "json",
    contentType: "application/json; charset=utf-8"
}).then(function mySucces(response) {

    $scope.allTracks = response.data;
    $scope.recentTracks = response.data.Tracks;
//now i want to luanch the function below that written in a different js file
//and pass parameters
 $rootScope.$broadcast('response-recieved', { response: response.data });

}, function myError(response) {
    $scope.allTracks = response.statusText;
});
});

现在,在您的不同js文件中,您可以按如下方式收听上述事件:

$scope.$on('response-recieved', function(event, args) {

    var res= args.response.Tracks;
    // do what you want to do
    startCration(res[0].Song, res[0].Artist); // call to your function.
});