在AngularJS中路由更改后再次运行功能

时间:2014-02-18 21:56:38

标签: angularjs routing

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

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{

            }

        }
}

1 个答案:

答案 0 :(得分:4)

我会使用$ routeChangeSuccess来做你正在谈论的事情

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