【问题标题】:Can I not use $ctrl. in angular component template我可以不用$ctrl吗?在角度组件模板中
【发布时间】:2016-06-08 06:41:40
【问题描述】:

我正在使用 angular 1.5,我想将我的 DOM 的一部分提取到 component
这是我到目前为止所做的:

angular.module('my-app').component("menuItem",{
    templateUrl : "lib/menu-item.tmpl.html",
    bindings : {
        index : "<",
        first : "<",
        last : "<",
        item : "=",
        onDelete : "&",
        onMoveUp : "&",
        onMoveDown : "&"
    },
    controller : function($scope) {
    }
});

模板看起来像这样:

<div>
    <aside class="sort-buttons">
        <ul>
            <li>
                <button ng-click="$ctrl.onMoveUp({index : $ctrl.index})"
                        ng-disabled="$ctrl.first">
                    <i class="icon icon-up"></i>
                </button>
            </li>
            <li>
                <button ng-click="$ctrl.onMoveDown({index : $ctrl.index})"
                        ng-disabled="$ctrl.last">
                    <i class="icon icon-down"></i>
                </button>
            </li>
        </ul>
    </aside>

    <div class="row">
        <button class="btn btn-danger btn-icon btn-remove"
                ng-click="$ctrl.onDelete({index : $ctrl.index})">
            <i class="icon icon-remove"></i>
        </button>
    </div>
</div>

我像这样使用这个组件(远未完成!):

<section class="container menu">
    <menu-item index="$index" first="$first" last="$last" item="item"
            on-delete="removeItem(index)"
            on-move-up="moveItemUp(index)"
            on-move-down="moveItemDown(index)"
            ng-repeat="item in menu">
    </menu-item>
    <!-- some other display details of `$ctrl.item` -->
</section>

我猜我有三个主要问题:

  1. 为什么我必须在我的模板中到处使用$ctrl?有$scope 那么为什么所有绑定都转到$ctrl 而不是$scope?有没有办法改变这种情况?
  2. 我能否以某种方式传入$index$first$last 之类的值?在我看来,将它们传递进去就像是一种“黄油”......
  3. 这是正确的方法吗?或者我应该使用指令?我知道组件有独立的范围,指令可以有非独立的范围。但是我可以在指令中混合/匹配吗(与控制器共享范围,但也可以添加我自己的函数以仅在指令/模板中使用?)

感谢您的帮助。

【问题讨论】:

  • 如果您投反对票,评论会很好吗?

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

为什么我必须在我的模板中到处使用 $ctrl?有 $scope 那么为什么所有的绑定都转到 $ctrl 而不是 $scope 呢?有没有 怎么改?

$scope 将随着 angular 2.0 消失。您没有义务使用 $ctrl。我建议您仍将“controllerAs”与命名控制器一起使用,以避免模板内部混淆。

controllerAs: "menuItemCtrl",
controller : function($scope) {
},

然后:

            <button ng-click="menuItemCtrl.onMoveUp({index : menuItemCtrl.index})"
                    ng-disabled="menuItemCtrl.first">
                <i class="icon icon-up"></i>
            </button>

要在控制器中使用有界变量,您必须使用 this

controller : function() {
    var self = this;
    // self.index contains your index
}

我能否以某种方式传入 $index、$first 和 $last 之类的值?它 在我看来,将它们传递进去就像是一种“黄油”......

我真的不明白你希望它们如何通过。

这甚至是正确的方法吗?还是应该使用指令?

当您面对可以显示为组件树的应用程序时,组件是最佳选择。

【讨论】:

  • 谢谢,为了清楚起见,我将使用controllerAs。我最终将向上/向下移动和删除等功能移动到组件外部,因此我不必传递 $index 值和许多事件。
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 2020-03-14
  • 2023-01-16
  • 2016-07-02
  • 2017-08-22
  • 2012-06-28
相关资源
最近更新 更多