0

我目前正在使用Angular 1.5库,并希望为简单的文本框创建一个组件,如下所示。

组件 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. 这是最佳实践@,或者=但我很好理解这个选项。

    一个。“@”(文本绑定/单向绑定)

    湾。“=”(直接模型绑定/双向绑定)

    C。“&”(行为绑定/方法绑定)

为什么采用这种方法?

我有大约 27 种输入类型的表单。我想创建一个包含所有字段标签、输入和错误容器的组件。

4

2 回答 2

1

有些事情非常令人困惑或完全错误:

您正在传递模型的名称,例如

<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;
        });
    }
});

至少我想知道为什么要将输入元素包装到组件中而只复制属性,你想实现什么?

于 2016-04-19T19:15:26.043 回答
0

Angular 团队建议通过使用单向绑定而不是双向绑定来对组件进行<范围@隔离=。就从组件中获取值而言,建议使用事件。

完整的详细信息基于组件的应用程序架构部分下

于 2016-04-20T20:16:04.923 回答