【问题标题】:How to define common bindings for all components of a same module in AngularJS?如何在 AngularJS 中为同一模块的所有组件定义通用绑定?
【发布时间】:2018-07-17 22:52:19
【问题描述】:

例如:

form.js

angular.module('myForm', []);

form-input-component.js

angular.module('myForm').component('inputField', {
  template: '<input type="text"></input>',
  bindings: {
    fieldName: '@',
    value: '='
  },
  controller: function () { }
});

form-select-component.js

angular.module('myForm').component('inputSelect', {
  template: '<select></select>',
  bindings: {
    fieldName: '@',
    value: '='
  },
  controller: function () { }
});

是否可以在form.js 中定义所有常见的绑定?

【问题讨论】:

  • 如果您尝试,您会收到任何错误吗?
  • 是的,我在缺少 fieldName 转换值时收到 $injector.modulerr 错误

标签: javascript angularjs components


【解决方案1】:

用js可以,但不能用角语法:

form.js

var commonBindings = {
   fieldName: '@',
   value: '='
}
angular.module('myForm', []);

form-input-component.js

angular.module('myForm').component('inputField', {
  template: '<input type="text"></input>',
  bindings: commonBindings,
  controller: function () { }
});

但您需要确保commonBindings var 具有全局范围(因此不要使用 IIFE 定义)并且需要更多绑定的组件必须在组件定义之前复制 value ad add 属性:

var customBindings = angular.copy(commonBindings);
customBindings.customVariable = "@";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 2017-05-14
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2017-05-27
    • 2019-03-26
    相关资源
    最近更新 更多