【问题标题】:Passing directives to Component in Angular 1.5在 Angular 1.5 中将指令传递给组件
【发布时间】:2016-04-19 18:00:10
【问题描述】:

我目前正在使用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. @= 是最佳实践,但我对此选项非常了解。

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

    b. "="(直接模型绑定/双向绑定)

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

为什么采用这种方法?

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

【问题讨论】:

    标签: angularjs angularjs-components


    【解决方案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;
            });
        }
    });
    

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

    【讨论】:

    • 感谢您的回复。无论您在寻找什么,都更新了我的问题?顺便说一句,你的答案不是回答问题
    【解决方案2】:

    Angular 团队建议使用单向绑定 &lt;@ 而不是双向绑定 = 来隔离组件的范围。就从组件中获取值而言,建议使用事件。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2018-06-14
      • 2016-05-16
      • 2020-04-01
      • 2017-07-14
      • 1970-01-01
      • 2016-08-21
      相关资源
      最近更新 更多