【问题标题】:Running function again after route change in AngularJS在 AngularJS 中更改路由后再次运行函数
【发布时间】:2014-02-18 21:56:38
【问题描述】:

所以我有一个主控制器和另外两个:

calculatorApp.controller('companybController', function($scope, $http) {
  //define the hardware data
  $scope.customs.prodoc = 'companyb';
});

calculatorApp.controller('companyaController', function($scope, $http) {
  $scope.customs.prodoc = 'companya';
});

// create the controller and inject Angular's $scope
calculatorApp.controller('mainController', function($scope, $http) {
  $scope.customs = {
    prodoc : ''
  };
});

但是在切换路线时 - 这有效:{{customs.prodoc}},但似乎使用它的函数在加载新视图时不会再次运行 - 导致应用程序使用旧值。

如何在视图更改后再次运行使用更改的$scope.customs.prodoc 的函数?

这是使用它的函数 - 我在 mainController 中有它,但不确定它是否属于那里。

$http.get($scope.customs.prodoc+'/products.json').success(function(thisdata) {
        $scope.products = []
        angular.forEach(thisdata, function(product) {
            $scope.products.push(product);
        });
        console.log($scope.products);
    });

$scope.change = function() {
// Suggest product
        $scope.suggested = {}
        var length = ($scope.products).length;
        for(i=0; i<length; i++){
            if($scope.products[i].CAMERA_MAX>=$scope.totals.cameras){
                $scope.suggested = $scope.products[i];
                break;
            }else{

            }

        }
}

【问题讨论】:

  • 使用它的函数在哪里?显示代码
  • 你确定控制器执行了吗?你能发布一个更完整的例子吗?
  • @DavideIcardi 我确定控制器已执行,因为我可以单独使用该变量(它显示来自当前控制器的新变量。)但使用该变量的函数不会再次运行。这就是我要解决的问题。
  • @IlanFrumer 再次嗨,Ilan!我在问题中发布了更多代码。

标签: angularjs routing


【解决方案1】:

我会使用 $routeChangeSuccess 来做你所说的

$scope.$on("$routeChangeSuccess", function($currentRoute, $previousRoute) {
    $scope.customs.prodoc = $scope.routeParams.prodoc;
});

【讨论】:

  • 酷——不过,我会把这个放在哪里?在calculatorApp.config 中?
  • 谢谢 - 一旦我将它插入两个控制器并运行 $scope.change(),它就可以完美运行
  • @itamar 你只需要把它放在目标控制器中。
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
相关资源
最近更新 更多