首页 > 解决方案 > AngularJS - 如何引用具有非常量名称的控制器

问题描述

假设我有几个控制器、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.

有没有办法处理这个错误或绕过它?

标签: htmlangularjs

解决方案


如发现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>

推荐阅读