AngularJS - How to reference a controller with a non-constant name [duplicate]

∥☆過路亽.° 提交于 2021-02-17 05:13:55

问题


Let's suppose I have several controllers, controller1, controller2, etc. and these all take similar data but perform very different tasks. An example of such a controller would be:

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

All the other controllers will instantiate limit, answer, hasresult and run. What this allows me to do is something like this:

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

Now, in my HTML file, what I'd like to do is this:

<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>

However, this approach results in an error like the one below:

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

Is there any way to deal with this error or get around it?


回答1:


As found 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);
      }
  };
}]);

You can use it like this:

<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>


来源:https://stackoverflow.com/questions/51307674/angularjs-how-to-reference-a-controller-with-a-non-constant-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!