javascript - 切换路线时停止 Controller 的事件

标签 javascript angularjs

我通过 AngularJS 创建单页应用程序,我发现了我的问题。我在路线 A 中通过 jQuery 每 2 分钟刷新一次数据。当我更改为其他路线时, Controller 中的该功能仍然有效。这是我的代码。

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 中的功能仍然有效(当我更改路线时,我看到功能打印 console.log)。我想在更改路线时停止 Controller 中的功能。谢谢大家的建议。 :)

最佳答案

我不太确定,但尝试使用 $stateProvider 而不是 $routeProvider。如果这样做,那么您需要 npm install angular-ui-router (它是 powerful 第三方模块)并替换 ngroute。我仅将 $routeProvider 用于 .otherwise 函数。您还可以使用 $stateProvider 做很多更酷的事情,例如 onEnter 和 onExit。另一件事是我建议您仅使用 Angular 而不是 jQuery。我真的不认为你同时使用两者有什么意义。使用 Angular 的双向数据绑定(bind)!另外,如果你真的想进入 Angular,那么我推荐 John Papa's style guide 。这些人知道他所说的如何制作出色的 Angular 应用程序。我希望这些信息有帮助!

关于javascript - 切换路线时停止 Controller 的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28599261/

相关文章:

javascript - 使用 AngularJS,我不想设置全局 $http.defaults.headers.common。我可以在每次调用 $resource 时发送我的自定义 header 吗?

angularjs - 如何清理测试之间的 Angular 缓存

javascript - 为什么这个分组 Angular 过滤器会导致摘要循环?

javascript 模拟 jQuery 语法

javascript - Angular Promise.all 在超时事件中不起作用

javascript - 在后面的asp.net代码中调用类点击功能

angularjs - 在 karma runner 的命令行中设置配置的 'browsers' 属性

javascript - 输入值在任意位置包含特定字符

javascript - 如何获取嵌套在两个赋值函数和 forEach 循环中的值?

javascript - 从 Angular $resource 访问实际服务器响应