Injecting required dependencies with ng-controller

后端 未结 3 1460
南旧
南旧 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:52

    The answer seems to be "no out of the box" way. Inspired by the responses, here is what I ended up implementing.

    Usage:

    Transcluded Template ID: {{id}}

    Implementation:

    .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;
    })
    

    I used a modified version of the code that implements uiSref (sometimes I wish angular would make these little nuggets part of the public API).

    ngComponent is kind of a "light-weight" directive that can be declared in your markup without having to actually build a directive. You could probably take it a little farther, but at some point you cross the line into needing to write a directive anyway.

提交回复
热议问题