Running function again after route change in AngularJS

别来无恙 提交于 2020-01-15 10:56:10

问题


So I have a main controller and two others:

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 : ''
  };
});

But when switching routes - this works: {{customs.prodoc}}, but it seems the function that uses it does not run again when the new view is loaded - causing the app to use the old values.

How do I run the function that uses the changing $scope.customs.prodoc again once the view has been changed?

Here's the function that uses it - I had it in mainController but not sure it belongs there.

$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:


I would use $routeChangeSuccess to do what you are talking about

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


来源:https://stackoverflow.com/questions/21866317/running-function-again-after-route-change-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!