当我使用ui-router时,我可以为多个子视图定义一个控制器吗?

时间:2013-09-17 11:30:41

标签: angularjs

我为ui-router定义了以下状态:

    var questions = {
        name: 'questions',
        url: '/questions',
        views: {
            'menu': {
                templateUrl: '/Content/app/questions/partials/menu.html',
            },
            'content': {
                templateUrl: '/Content/app/common/partials/empty.html',
            },
            'status@': {
                templateUrl: '/Content/app/questions/partials/status.html',
            }
        }
    }

    var questionsContent = {
        name: 'questions.content',
        parent: 'questions',
        url: '/:content',
        views: {
            'content@': {
                templateUrl: function (stateParams) {
                    var isNumber = !isNaN(parseFloat(stateParams.content));
                    return isNumber ? '/Content/app/questions/partials/detail.html' :
                                      '/Content/app/questions/partials/content.html'
                },
            },

        }
    }

我想为此定义一个控制器。

我见过这样的例子,每个视图都有这样做:

    'content@': {
                templateUrl: '/Content/app/home/partials/content.html',
                controller: 'HomeContentController',
            }

我是否可以使用一个用于所有的控制器 视图和那样做我需要每次为每个指定控制器 视图。

当/:内容值发生变化时,如何检测控制器中的状态变化 然后做点什么?

2 个答案:

答案 0 :(得分:3)

我不知道watch状态更改的内置方式,但您可以使用LocationService包裹$state.transitionTo并从那里广播内容:

function LocationService($http, $state) {

    this.transitionTo = function ($scope, state) {
        $state.transitionTo(state);
        $scope.$root.$broadcast('stateTransition', state);
    };
}

myModule.service('LocationService', ['$http', '$state', LocationService]);

然后,在您使用href="#root.somestate"

的视图中使用ng-click="goto('root.somestate')"的锚点。
$scope.$watch('stateTransition', function(state) {
    console.log('transitioning to ' + state);
});

$scope.goto = function(state) {
    locationService.transitionTo($scope, state);
}

在您的控制器中。

答案 1 :(得分:1)

I think you should try following code.
$stateProvider
  .state('report',{
    views: {
      'filters': {
        templateUrl: 'report-filters.html',
        controller: function($scope){ ... controller stuff just for filters view ... }
      },
      'tabledata': {`enter code here`
        templateUrl: 'report-table.html',`enter code here`
        controller: function($scope){ ... controller stuff just for tabledata view ... }
      },
      'graph': {
        templateUrl: 'report-graph.html',
        controller: function($scope){ ... controller stuff just for graph view ... }
      },
    }
  })