【问题标题】:Angular 1.5 components and ui-router 1.0: Add attributes to inserted dom elementAngular 1.5 组件和 ui-router 1.0:向插入的 dom 元素添加属性
【发布时间】:2016-09-28 08:14:11
【问题描述】:

在 Angular 1.5 中,引入了 .component() ,这似乎被认为是一种很好的做法。我目前正在迁移到允许(并建议)路由到组件的 ui-router 1.0。 所以我重构了一个控制器/模板路由到一个效果很好的组件路由器:组件“示例”被注入到它自己的 DOM 节点中的 ui-view 容器中:

但是,这破坏了我的布局(使用角材料)。我使用的解决方法是简单地复制和使用 css 类角度材料用于插入节点上的布局。但是,我认为这是一个“hacky”解决方案:例如,如果角材料改变它的布局模块怎么办?

更好的解决方案是将布局属性甚至 css 类添加到“示例”元素。但我该怎么做?这可能吗?

我认为这个问题与以下内容有关,我提供了针对特定问题的解决方法。但我对更通用的解决方案感兴趣:Using angular component breaks material layout

【问题讨论】:

  • 面临同样的问题。

标签: angularjs angular-ui-router angular-material


【解决方案1】:

我在 Angular 1.5 项目中也遇到了同样的问题,我还使用了 angular-ui-router 和 Angular Material 组件。一种可能的解决方案是简单地使用string-based binding,将两个属性绑定到组件中:layoutflex。当您通过以下方式指定您的 ui 路由状态时,您可以为这两个绑定属性(通常分别为 'row' 和 '100' )提供值:

var exampleState = {
    name: 'examplestate',
    url: '/',             // change this to your desired path
    component: 'example',
    resolve: {
        layout: function () {
            return 'row'; // you can change this value depending on your UI requirements
        },
        flex: function () {
            return '100'; // you can change this value depending on your UI requirements
        }
    }
};

在模块的 config 方法中,您以标准方式定义您的 exampleState:

$stateProvider.state(exampleState);

最后,在组件定义中,当您定义绑定时,将这两个属性添加到绑定属性列表中。 打字稿中的示例:

export class ExampleComponent implements ng.IComponentOptions {

    public bindings: any;
    public controller: any;
    public template: string;

    constructor() {
        this.bindings = {
            layout: '@',
            flex: '@'
        };
        this.controller = ExampleComponentController;
        this.template = ExampleViewTemplate;
    }
}

您可以按照通常的方式将此组件添加到您的 Angular 模块中:

.component('example', new ExampleComponent());

这将在 DOM 中生成以下 HTML 元素(由 angular-ui-router 自动创建):

<example layout="row" flex="100" class="ng-scope ng-isolate-scope layout-row flex-100">

因此,通过这种方式,您无需在代码中插入任何手动 CSS 样式。您正在组件元素上使用标准的 Angular Material 属性。

【讨论】:

  • 嗨,彼得,感谢您的建议,很抱歉回复晚了。您的解决方案确实非常有用。
猜你喜欢
  • 2016-10-19
  • 2016-12-09
  • 2020-06-14
  • 1970-01-01
  • 2016-10-05
  • 2010-09-17
  • 2013-08-21
  • 1970-01-01
  • 2017-02-28
相关资源
最近更新 更多