Entering required dependencies with ng controller

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

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

registered:

.state('widget',
       controller: 'widget',
       template: '/widgetTemplate.html'

We are faced with a situation where we like to reuse this controller as part of the template:

<div ng-controller="widget" ng-include="/widgetTemplate.html"></div>

but there seems to be no easy way to insert a mocking $ stateParams object with the appropriate id. Sort of:

<div ng-controller="widget" ng-inject="{$stateParams: {id: 1234}}" ng-include="/widgetTemplate.html"></div>

Beyond writing a custom directive that complements the ng controller or refactoring our code to use inherited areas, are there any ready-made ways to do this?

+4
source share
3 answers

, . ng-controller , -.

"", , , .

( : ):

.directive("ngInject", function($parse, $interpolate, $controller, $compile) {
  return {
    terminal: true,
    transclude: true,
    priority: 510,
    link: function(scope, element, attrs, ctrls, transclude) {

      if (!attrs.ngController) {
        element.removeAttr("ng-inject");
        $compile(element)(scope);
        return;
      }

      var controllerName = attrs.ngController;

      var newScope = scope.$new(false);

      var locals = $parse(attrs.ngInject)(scope);
      locals.$scope = newScope;

      var controller = $controller(controllerName, locals);

      element.data("ngControllerController", controller);

      element.removeAttr("ng-inject").removeAttr("ng-controller");
      $compile(element)(newScope);
      transclude(newScope, function(clone){
        element.append(clone);
      });
      // restore to hide tracks
      element.attr("ng-controller", controllerName); 
    }
  };
});

, :

<div ng-controller="MainCtrl">
  {{name}}
  <div ng-controller="SecondCtrl" ng-inject="{foo: name, bar: 'bar'}">
  </div>
</div>

, , :

.controller("SecondCtrl", function($scope, foo, bar){
});

plunker

+4

, , , , .

, . , , :

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

, :

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

, :

<widget widget-id="789"></widget>

: http://plnkr.co/edit/0rSfr4jt48tSyHXwgnS5?p=preview

+1

" ". , .

:

<div ng-component="test.controller({$stateParams: { id: 1}})" template="test.html"></div>

<div ng-component="test.controller({$stateParams: { id: 2}})">
  <div>Transcluded Template ID: {{id}}</div>
</div>

:

.directive('ngComponent', function($compile, $parse, $controller, $http, $templateCache) {
return {
  restrict: 'A',
  transclude: true,
  scope: true,
  compile: function(tElement, tAttr) {
    return function(scope, element, attrs, ctrl, transclude) {

      //credit for this method goes to the ui.router team!
      var parseControllerRef = function(ref, current) {
        var preparsed = ref.match(/^\s*({[^}]*})\s*$/),
          parsed;
        if (preparsed) ref = current + '(' + preparsed[1] + ')';
        parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
        if (!parsed || parsed.length !== 4) throw new Error("Invalid component ref '" + ref + "'");
        return {
          controller: parsed[1],
          paramExpr: parsed[3] || null
        };
      };

      var ref = parseControllerRef(attrs.ngComponent);
      scope.$eval(ref.paramExpr);
      if(attrs.template) {
        $http.get(attrs.template, {cache: $templateCache}).then(function(result){
          var template = $compile(result.data)(scope);
          element.append(template);
        },
        function(err){
            //need error handling
        });
      }
      else {
          transclude(scope, function(clone) {
            element.append(clone);
          })
      }

      var locals = {
        $scope: scope
      }

      angular.extend(locals, scope.$parent.$eval(ref.paramExpr));
      var controller = $controller(ref.controller, locals);
      element.data("ngControllerController", controller);

      //future:  may even allow seeing if controller defines a "link" function or 
      //if the attrs.link parameter is a function.
      //This may be the point of demarcation for going ahead and writing a 
      //directive, though.

    };
   }
 };
})
.controller('test.controller', function($scope, $stateParams) {
    $scope.id = $stateParams.id;
})

, uiSref ( , angular API).

ngComponent is a kind of “lightweight” directive that can be declared in your markup without actually building the directive. You could probably take it a little further, but at some point you cross the line to write a directive anyway.

+1
source

All Articles