AngularJS,来自变量的嵌套控制器

AngularJS, nested controllers from variable

本文关键字:嵌套 控制器 自变量 AngularJS      更新时间:2023-09-26

通常,我想做的是使用变量初始化ng-repeat内的嵌套ng-controller

JSFiddle

JS

angular.module('app',[])
.controller('main',function($scope){
    angular.extend($scope,{
        name:'Parent Controller',
        items:[
            {name:'nested2'},
            {name:'nested1'}
            ]
    });
})
.controller('nested1',function($scope){
    $scope.name = "Name1";
})
.controller('nested2',function($scope){
    $scope.name = "Name2";
});

我想要这个:

<div ng-controller="main" ng-app='app'>
    Nested: {{name}}
    <div ng-controller="nested1">{{name}}</div>
    <div ng-controller="nested2">{{name}}</div>
</div>

变成这样:

<div ng-controller="main">
    Nested: {{name}}
    <div ng-repeat="item in items">
        <div ng-controller="item.name">{{name}}</div>
    </div>
</div>

问题:这种方式不起作用。这两种方法都不起作用,我在谷歌上搜索了一个小时左右后就试过了

有什么"合法"且好的方法可以实现这一点吗?

我想,目前还没有真正的方法,使用角度特征。您可以创建一个指令并使用未记录的动态控制器功能controller:'@', name:'controllerName'。但这种方法不会评估提供控制器名称的绑定或表达式。我能想到的是通过实例化提供的控制器并将其设置为元素来进行破解。

示例:-

.directive('dynController', function($controller){
  return {
    scope:true, //create a child scope
    link:function(scope, elm, attrs){
      var ctrl =scope.$eval(attrs.dynController); //Get the controller
      ///Instantiate and set the scope
      $controller(ctrl, {$scope:scope})
     //Or you could so this  well
     //elm.data('$ngControllerController', $controller(ctrl, {$scope:scope}) ); 
    }
  }
});

在你看来:-

  <div ng-controller="main">
    <div ng-repeat="item in items">
    Nested:
          <div dyn-controller="item.name" ng-click="test()">{{name}}</div>
    </div>
  </div>

演示

请注意,我已经从执行ng重复的元素更改了ng控制器的位置,由于ng重复(1000)的优先级高于ng控制器(500),因此ng重复的范围将占上风,您最终不会重复任何内容。

看着它

投入了更多的几个小时,检查角度源等。

ng-controller的表达式根本没有被求值。

这是我发现的最好的方法:

HTML:

    <div ng-controller="main">
        Nested: {{name}}
        <div ng-repeat="item in items">
            <div ng-controller="nested" ng-init="init(item)">{{name}}</div>
        </div>
    </div>

JS:

angular.module('myApp', [])
    .controller('main', function ($scope, $controller) {
        angular.extend($scope, {
            name: 'Parent Controller',
            items: [
                {name: 'nested2'},
                {name: 'nested1'}
            ]
        });
    })
    .controller('nested', function ($scope, $controller) {
        angular.extend($scope, {
            init: function (item) {
                $controller(item.name, {'$scope': $scope});
            }
        });
    })
    .controller('nested1', function ($scope) {
        $scope.name = 'test1';
    })
    .controller('nested2', function ($scope) {
        $scope.name = 'test2';
    });