簡體   English   中英

在Angular 1.5中將指令傳遞給Component

[英]Passing directives to Component in Angular 1.5

我目前正在使用Angular 1.5庫,並希望為如下所示的簡單Text Box創建一個組件。

組件JS

'use strict';

angular
    .module('components')
    .component('inputBox', {
        bindings: {
            label: '@',
            name: '@',
            type: '@',
            classes: '@',
            placeholder: '@',
            maxlength: '@'
        },
        controllerAs: 'field',
        templateUrl: 'app/components/inputBox.html'
    });

組件模板

<input type="{{field.type || 'text'}}"  
            class="form-control {{field.classes}}" 
            id="{{field.name}}" 
            name="{{field.name || 'unnamed'}}" 
            maxlength="{{field.maxlength}}" 
            placeholder="{{field.placeholder}}" />

所有模板中的用法。

<input-box 
    label="Enter an account"
    name="accountNumber"
    type="number"
    classes="form-control"
    placeholder="Account Number"
    maxlength="20"

    // directives
    ng-model="accountNumber"
    ng-custom1="value1" 
    ng-custom2="value2" 
    ng-custom-validator="value4" />

我有兩個問題,下面是我需要最佳實踐的地方。

  1. 我想使使用指令模板中的所有指令都擴展而不是組件的一部分。
  2. 這是@=最佳做法,但我對此選項有很好的了解。

    一種。 “ @”(文本綁定/單向綁定)

    b。 “ =”(直接模型綁定/雙向綁定)

    C。 “&”(行為綁定/方法綁定)

為什么采用這種方法?

我有大約27種具有多種輸入類型的表格。 我想創建將具有所有字段標簽,輸入和錯誤容器的單個組件。

有些事情很令人困惑或錯誤:

您正在傳遞模型名稱,例如

<input-box modelname="account.number"...

並嘗試將其用於:

<input type="{{field.type || 'text'}}" 
        ng-model="account.number" ...

您沒有使用模型名,而是嘗試訪問未定義的對象變量account.number (至少在示例中未定義),該變量不再動態。

如果您想直接傳遞模型,請執行以下操作:

angular
.module('components')
.component('inputBox', {
    bindings: {
        model: '=',
        ...
    },
    controllerAs: 'field',
    templateUrl: 'app/components/inputBox.html'
});

<input-box model="account" ... />

在您的組件模板中:

<input ng-model="model" ... />

關於第二個問題:你不能

<input ... {{field.attribs}} />

您可以使用attrs並將其復制到輸入元素中:

angular
.module('components')
.component('inputBox', {
    bindings: {
        model: '=',
        ...
    },
    controllerAs: 'field',
    templateUrl: 'app/components/inputBox.html',
    controller: function($scope, $element, $attrs) {
        angular.forEach($attrs, function(key, value){
            $element[key] = value;
        });
    }
});

至少我想知道為什么將輸入元素包裝到組件中,而僅復制屬性,您想要實現什么?

Angular團隊建議使用單向綁定<@而不是雙向綁定=來隔離組件的范圍。 就從組件中獲取價值而言,建議使用事件。

全部細節在這里的部分基於組件的應用程序體系結構

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM