【问题标题】:custom angularjs directive with scope and ng-controller具有范围和 ng-controller 的自定义 angularjs 指令
【发布时间】:2016-07-29 10:12:02
【问题描述】:

我想创建同时具有作用域参数和 ng-controler 的指令。

这是该指令的外观:

<csm-dir name="scopeParam" ng-controller="RegisteredController">
   <!--Here I want to have content--> 
   {{name}}
</csm-dir>

我在我的应用程序某处声明了“RegistertedController”。

angular.module('app')
    .controller('RegisteredController', ['$scope', function ($scope) {
        //$scope.name should be accessible here
    }]);

我正在尝试声明指令:

angular.module('app')
    .directive('csmDir', [function () {
        return {
            restrict: 'AE',
            replace: true,
            transclude: true,
            scope: {
                name: '='
            },
            template: '<section class="layout"><ng-transclude></ng-transclude></section>',
            link: function (scope, element, attr, ctrl, transclude) {
                element.find('ng-transclude').replaceWith(transclude());
                //here I also need scope.name parameter
            }
       };
    });

我得到错误:

Multiple directives [ngController, csmDir] asking for new/isolated scope on: <csm-dir name="scopeParam" ng-controller="RegisteredController">

现在这个错误信息量很大,我知道它的角度不能像我想的那样工作。

我可以从指令中删除“范围:{..}”参数并在控制器中定义它,但这不是我需要的。

我需要的基本上是为自定义指令提供 ng-controller,然后为该控制器提供额外的范围变量。

我怎样才能做到这一点?

【问题讨论】:

  • AngularJS 组件不够用吗?

标签: javascript angularjs angular-directive ng-controller


【解决方案1】:

你必须用标签包装你的指令并将控制器放在那里。

<div ng-controller="RegisteredController">
   <csm-dir name="scopeParam">
       <!--Here I want to have content--> 
       {{name}}
   </csm-dir>
</div>

没有办法在一个标签中获得两个独立的作用域。

【讨论】:

  • 是的,可以,但我想知道是否可以将 ng-controller 指令包装在另一个指令中
  • 你可以做出有趣的事情。创建父指令并将其与控制器链接。然后使用 require 选项添加子指令。并访问控制器。没事吧?
猜你喜欢
  • 2015-03-17
  • 2014-10-23
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 2013-09-04
相关资源
最近更新 更多