2017-04-30 82 views
2

後,我用Plangular這是使用角JS和的SoundCloud的API來播放一些歌曲指令。當然,它需要Soundcloud jdk,angular和它的js。重裝腳本Ajax調用

我tryed然後以這種方式通過Ajax加載在一個div動態外部內容:

$(document).ready(function(){ 
    $("body").on('click', '#chart_best',function(){ 
     $.ajax({url: "chart_best.html", success: function(result){ 
      $(".container").html(result); 
     }}); 
    }); 
    $("body").on('click', '#chart_best_indie_pop',function(){ 
     $.ajax({url: "chart_best_indie_pop.html", success: function(result){ 
      $(".container").html(result); 
     }}); 
    }); 
    $("body").on('click', '#chart_best_punk',function(){ 
     $.ajax({url: "chart_best_punk.html", success: function(result){ 
      $(".container").html(result);    
     }}); 
    }); 
}); 

新的內容是否正確裝入,但玩家簡單不起作用。這聽起來像需要在ajax調用之後重新加載JS。我嘗試使用.live但它不起作用。也嘗試刪除腳本並通過$ .getScript()重新加載它們,但仍然無法使用該播放器。 我複製的問題,在這個項目中:https://codepen.io/GoingSolo/project/editor/DNVyJD/如果你左邊的列表中點擊加載新的內容,玩家簡單停止工作。 哪一個是重新加載所有腳本的最佳方式Plangular需要在我的ajax調用之後工作?

+0

使用jQuery做的這一切都是在角度應用 – charlietfl

+0

@charlietfl感謝的答覆只是完全錯誤的做法,你可以更好地解釋我爲什麼它是一個不錯的辦法?我應該用什麼來代替jquery來做一些Ajax調用? – GoingSolo

+1

應該使用角度方法和角度'$ http',並且可能在指令內執行此操作。強烈建議閱讀[「在AngularJS思考:」如果我有一個jQuery的背景(http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) – charlietfl

回答

1

有興趣的人我是如何解決這個,基本上,所建議的,我改變了我的Ajax調用到angularjs $http這樣的:

gsplayer.controller('SearchBar', function($scope, $http) { 

    $scope.chart_best = function() { 
     $scope.dataLoaded = false; 
    $http.get("../themes/replay/chart_best.php").then(function (response) { 
     $scope.myData = response.data; 
     $scope.chartTitle = "Top 20 Tracks"; 
     $scope.dataLoaded = true; 
    }); 
    }; 

    $scope.chart_best_indie_pop = function() { 
     $scope.dataLoaded = false; 
    $http.get("../wp-content/themes/replay/chart_best_indie_pop.php").then(function (response) { 
     $scope.myData = response.data; 
     $scope.chartTitle = "Best Indie Pop Tracks"; 
     $scope.dataLoaded = true; 
    }); 
    }; 

    $scope.chart_best_punk = function() { 
     $scope.dataLoaded = false; 
    $http.get("../wp-content/themes/replay/chart_best_punk.php").then(function (response) { 
     $scope.myData = response.data; 
     $scope.chartTitle = "Best Punk Tracks"; 
     $scope.dataLoaded = true; 
    }); 
    };  
}); 

然後我不得不重寫三個php頁,以獲取json格式的所需數據並訪問myData

+1

好的解決方案。未來的技巧,遠離使用jQuery與angularJS結合使用,因爲所有jQuery事件都不會觸發摘要循環(變更檢測)嘗試儘可能多地使用角度服務,因爲它們會執行**觸發變化檢測。這不會讓你不知道爲什麼你的視圖或模型沒有像你期望的那樣更新。 – Abdel

+0

@Abdel謝謝你的提示。有沒有關於如何在http.get之後更改url的提示?我閱讀路由文檔,但我不知道如何處理它在我的工作代碼 – GoingSolo

+0

真的取決於你使用的路由器!就我個人而言,我會建議調查[ui-router](https://github.com/angular-ui/ui-router),因爲它仍在維護中。如果你完成了你的路由設置,你可能需要在你的'http.get'的回調中使用'$ state.go('routeName')'來使用'$ state'服務!這是他們的[文檔](https://github.com/angular-ui/ui-router/wiki) – Abdel