Injecting required dependencies with ng-controller

后端 未结 3 1466
南旧
南旧 2020-12-17 03:14

Using ui.router, we have a controller for a state:

controller(\'widget\', function($repository, $stateParams){
    $scope.widget = $repository.get($statePara         


        
3条回答
  •  孤城傲影
    2020-12-17 03:54

    There have been some places where I've used a controller for both a state and a directive that looks to be similar to what you're trying to do.

    You could define a directive that re-uses your controller and template. It adds what you'd want set from the state as a parameter that's available on the scope:

    .directive('widget', function(){
      return {
        restrict: 'E',
        template: '
    id in directive {{widgetId}}
    ', controller: 'widget', scope: { widgetId:'=' } }; })

    Then update your controller to look in the scope or state params:

    .controller('widget', function($scope, $stateParams){
      $scope.widgetId = $scope.widgetId || $stateParams.id;
    })
    

    Finally, you can use it to reference a widget by a specific id:

    
    

    Here's a plunker with a sample: http://plnkr.co/edit/0rSfr4jt48tSyHXwgnS5?p=preview

提交回复
热议问题