Best Practices: Should I use ng-switch for this? [closed]
Asked Answered
S

1

6

I've got this object in Angular.

$scope.columns = {
    workspace: {
        title: "Workspace",
        type: "workspace",
        activities: []
    },
    alerts: {
        title: "Alerts",
        type: "alert",
        activities: []
    },
    main: {
        title: "Main Feed",
        type: "main",
        activities: []
    }
};

And in my HTML I need to loop through it to dynamically create a series of columns in my app (think something like Trello)

Each type is a reference to a custom directive.

I'm trying to figure out the best way to place my directives.

Based on this data, is the code below an appropriate way to handle dynamically creating these?

<div ng-repeat="(key, obj) in columns">

    <div ng-switch on="obj.type">
        <workspace-feed ng-switch-when="workspace" />
        <alert-feed ng-switch-when="alert" />
        <main-feed ng-switch-when="main" />
        <filter-feed ng-switch-when="filter" />
    </div>

</div>

I'd love to be able to do something like... <{{obj.type}}-feed /> but I'm not sure if this is valid, or if there's a better way to create this.

Thoughts are much appreciated!

Shrewmouse answered 7/7, 2015 at 20:37 Comment(5)
What's wrong with ngSwitch?Scyphate
That looks alright. How different is each feed? Maybe you don't need separate directives for each feed - maybe you can use a single directive which dynamically loads a template based on the column type. It depends on your columns.Faradic
@dsfq - nothing's wrong with it, I'm just looking for the 'best practices' for something like this.Shrewmouse
@Faradic - I had no idea I could dynamically load templates. That sounds like exactly what I need. Thanks!Shrewmouse
could you show use what your directive is doing?Kareenkarel
F
2

What you have so far looks fine.

Depending on how different your columns are, you may opt to use just one directive which dynamically loads a template instead of multiple directives. For example, take a look at ng-include:

<div ng-include="'columns/' + column.type + '.html'"></div>
Faradic answered 7/7, 2015 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.