简体   繁体   中英

Changing variables in controller on route change?

I have a template and a few views that are rendered based on their route:

popApp.controller('HomeCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {    
  $scope.showNow = true;
}]);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/signup', {
      controller:'HomeCtrl',
      templateUrl:'partials/newAccountStage.html'
    })
    .when('/', {
      controller:'HomeCtrl',
      templateUrl:'partials/home.html'
    });
}]);

In my template, I display some elements I'd like to display most of the time, but hide when certain routes are followed:

<div ng-show="showNow"></div>

Basically when the user is on the /signup route I'd like to hide some elements.

What's the most angular way to approach this?

It is a well known practice to separate controllers for any main view that you want. You could go with the $routeProvider , as shown.

popApp.controller('HomeCtrl', [
    '$scope', 
    '$routeParams', 
    '$http', 
    function($scope, $routeParams, $http) {    
        $scope.showNow = true;
    }
]);

popApp.controller('SignupCtrl', [
    '$scope', 
    '$routeParams', 
    '$http', 
    function($scope, $routeParams, $http) {    
        $scope.showNow = true;
    }
]);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/signup', {
      controller:'SignupCtrl',
      templateUrl:'partials/newAccountStage.html'
    })
    .when('/', {
      controller:'HomeCtrl',
      templateUrl:'partials/home.html'
    });
}]);

Another practice is to use the $stateProvider , in the case you have this signup capability inside of another controller and you want to render the screen something different if the user has not signed up and you want to change the "state" of the page. Then SignupCtrl would become a state of HomeCtrl , where you would set the state as 'not signed up' and it could use the SignupCtrl.

Here's a link for $stateProvider.

And an example of how that syntax might look:

$stateProvider.state('not signed up', {
  template: 'partials/newAccountStage.html',
  controller: SignupCtrl
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM