【问题标题】:AngularJS - How to reference a controller with a non-constant name [duplicate]AngularJS - 如何引用具有非常量名称的控制器[重复]
【发布时间】:2018-12-20 19:19:05
【问题描述】:

假设我有几个控制器,controller1controller2 等,它们都采用相似的数据,但执行的任务却截然不同。这种控制器的一个例子是:

angular.module('myApp').controller('controller1', ['$scope', function($scope) {
    $scope.limit = undefined;
    $scope.answer = undefined;
    $scope.hasresult = false;

    $scope.run = function() {
        // Do some controller-specific stuff here...
    }
}]);

所有其他控制器将实例化limitanswerhasresultrun。这允许我做的是这样的:

angular.module('myApp').controller('controller_indexer', ['$scope', function($scope) {
    $scope.controllers = 
    [
        {
            index: 1,
            name: 'Some special name',
            result: 'Some results from {{limit}} --> {{answer}} here'
        }
    ];
}]);

现在,在我的 HTML 文件中,我想做的是:

<div ng-app="myApp" ng-controller="controller_indexer">
    <div ng-repeat="x in controllers">
        <div ng-controller="controller{{x.index}}">
            <!-- do some stuff here -->
        </div>
    </div>
</div>

但是,这种方法会导致如下错误:

The controller with the name 'controller{{x.index}}' is not registered.

有什么方法可以处理或绕过这个错误?

【问题讨论】:

标签: html angularjs


【解决方案1】:

如发现here

mainApp.directive('ngDynamicController', ['$compile', '$parse',function($compile, $parse) {
  return {
      scope: {
          name: '=ngDynamicController'
      },
      restrict: 'A',
      terminal: true,
      priority: 100000,
      link: function(scope, elem, attrs) {
          elem.attr('ng-controller', scope.name);
          elem.removeAttr('ng-dynamic-controller');

          $compile(elem)(scope);
      }
  };
}]);

你可以这样使用它:

<div class="col-xs6 col-sm-5 col-md-4 col-lg-3" ng-repeat="box in boxes">
<div ng-include src="'/assets/js/view/box_campaign.html'" ng-dynamic-controller="box.type"></div>
</div>

【讨论】:

  • 我不明白这是一个解决方案。目前,它似乎所做的只是用ng-controller 替换您的指令名称并编译结果。这不会简单地产生与我看到的相同的错误吗?
  • @Woody1193 看起来它可能有效。你试过了吗?
  • 他错过了插值线;一旦我补充说它有效。我更新了他的解决方案以反映变化
  • @Woody1193 我对$compile$interpolate 不太熟悉,但如果scope.name 包含所需控制器的名称(而不是像controller{{ index }} 这样的角度表达式,那么我不知道)不认为有必要插值。
  • @JLRishe 但这就是问题的重点。 scope.name 必须包含角度表达式,因此需要插值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多