【问题标题】:Dynamic adding controller to ng-include将控制器动态添加到 ng-include
【发布时间】:2015-09-07 22:18:56
【问题描述】:

这是改变ng-include控制器的动态方式吗?

我的应用程序允许用户创建页面一些内容和控制器。我可以更改 ng-include src 但我不知道如何动态关联新控制器。以下代码不起作用:

<div ng-app="MyApp">
    <div ng-controller="ParentController">
        <select ng-model="currentItem" ng-options="item as item.url for item in items track by item.url">
        </select>
        {{ currentItem }}
        <div ng-include src="currentItem.url" ng-controller="currentItem.controller"></div>
    </div>
</div>

我有以下 JS:

var app = angular.module("MyApp",[]);

app.controller('ParentController', ['$scope',function($scope){
    $scope.items = [{
        url: 'page1.html',
        controller: 'Page1Controller'
    },
    {
        url: 'page2.html',
        controller: 'Page2Controller'
    }];
    $scope.currentItem = {};
}]);

app.controller('Page1Controller', ['$scope',function(){
    alert('Page1');
}]);

app.controller('Page2Controller', ['$scope',function(){
    alert('Page2');
}]);

【问题讨论】:

  • 使用指令而不是 ng-include,这就是它们的用途。

标签: javascript angularjs


【解决方案1】:

我已经通过使用指令来完成:

<div ng-include src="currentItem.url" dyn-controller="currentItem.controller"></div>

JS 指令:

app.directive('dynController', ['$compile', '$parse',function($compile, $parse) {
  return {
    restrict: 'A',
    terminal: true,
    priority: 100000,
    link: function(scope, elem, attrs) {
            // Parse the scope variable
            var name = $parse(elem.attr('dyn-controller'))(scope);
            elem.removeAttr('dyn-controller');
            elem.attr('ng-controller', name);

            // Compile the element with the ng-controller attribute
            $compile(elem)(scope);       
  };
}]);

这里的诀窍是观察属性变化,添加ng-controller,然后编译元素。

感谢

How to watch property in attrs of directive

Dynamic NG-Controller Name

【讨论】:

  • 一年后,这正是我所需要的。让我们希望它有效:) 谢谢
  • terminal = true 是让它工作的关键
【解决方案2】:

以下项目数组是一个普通对象数组,它有两个字段:url 和控制器,都包含字符串值。

 $scope.items = [{
        url: 'page1.html',
        controller: 'Page1Controller'
    },... ]

您真正需要的是对函数的引用,这可以通过$injector 服务来实现。

尽管这可能有效,但我不明白您为什么不使用 ParentController 来更改数组中的对象(或 directive)。

【讨论】:

  • 我没有使用ParentController,因为项目数组和控制器声明是由我的用户动态创建的。
  • 一定误解了你的问题。但是您确实声明这是您“已经”拥有的代码。尽管如此,您只是绑定了一个字符串而不是一个控制器函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
相关资源
最近更新 更多