停止控制器's切换路由时的活动

Stop Controller's activity when switch route

本文关键字:路由 活动 控制器      更新时间:2024-01-23

我用AngularJS创建了单页应用程序,发现了我的问题。我在路由A中使用jQuery每2分钟刷新一次数据。当我切换到其他路由时,控制器中的该功能仍在工作。这是我的密码。

App.js

var newsapp = angular.module('newsAppMD', ['ngRoute']);
newsapp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/news', {
        templateUrl: 'templates/news.html',
        controller: 'imageNewsCtrl'
    }).
    when('/news/:nameCat', {
        templateUrl: 'templates/news-thumbnail.html',
        controller: 'newsPageCtrl'
    }).
    otherwise({
        redirectTo: '/news'
    });
}]);
newsapp.controller('imageNewsCtrl', function($scope, $http, $interval, $timeout ) {
    $('#bottom-bar').find('#epg').hide();
    $scope.updateTimeEPG = 120000;
    $scope.fetchFeed = function() {
  $http.get("http://wi.th/thaipbs_tv_backend/epg_forJS.php").success(function(response) {
        $scope.items = response.Schedule;
        console.log($scope.items);
        $timeout(function() { $scope.fetchFeed(); }, $scope.updateTimeEPG);
    }).then(function() {
            $('#bottom-bar').find('.loading').hide();
            $('#bottom-bar').find('#epg').show();
    });
};
    $scope.fetchFeed();
});
newsapp.controller('newsPageCtrl', function($scope, $http, $location) {    
    // blah blah blah
}]);

我选择/news imageNewsCtrl工作。当我切换到其他路由时,imageNewsCtrl中的功能仍然有效(当我更改路由时,我看到了功能print console.log)。我想在改变路线时停止控制器中的功能。谢谢大家的建议。:)

我不太确定,但尝试使用$stateProvider而不是$routeProvider。如果你这样做了,那么你需要npm安装angular ui路由器(它是一个强大的第三方模块)并更换ngroute。我只为.ethere函数使用$routeProvider。您还可以使用$stateProvider执行更多很酷的操作,如onEnter和onExit。另一件事是,我建议您只使用Angular而不是jQuery。我真的不认为你同时使用这两种方法有什么意义。使用Angular的双向数据绑定!此外,如果你真的想进入Angular,那么我推荐John Papa的风格指南。这些家伙知道他在说什么来制作一个伟大的Angular应用程序。我希望这些信息能有所帮助!