简体   繁体   English

更改路线时更改控制器中的变量?

[英]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. 基本上,当用户在/ signup路线上时,我想隐藏一些元素。

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. 您可以使用$routeProvider ,如图所示。

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. 另一种做法是使用$stateProvider ,如果您在另一个控制器中具有此注册功能,并且如果用户尚未注册并且要更改页面的“状态”,则希望使屏幕呈现不同的$stateProvider Then SignupCtrl would become a state of HomeCtrl , where you would set the state as 'not signed up' and it could use the SignupCtrl. 然后SignupCtrl将成为状态HomeCtrl ,在那里你会设置状态为“未注册”,它可以使用SignupCtrl。

Here's a link for $stateProvider. 这是$ stateProvider的链接。

And an example of how that syntax might look: 以及该语法的外观示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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