0

I have some notify message to display, which using difference template by difference notify type.

Now I have make the template into directives, I display the right directive by using ng-switch, like this :

<ul>
<li ng-repeat="notify in notifies | orderBy: 'id'" >
    <div ng-switch on="notify.type">
        <div ng-switch-when="1">
            <span ng-notify-A ng-notify="notify"></span>
        </div>
        <div ng-switch-when="2">
            <span ng-notify-B ng-notify="notify"></span>
        </div>
        <div ng-switch-when="3">
            <span ng-notify-C ng-notify="notify"></span>
        </div>
    </div>
</li>
</ul>

Yet I really think it can be better, with setting java script logic then output, instead of ng-switch. It should be work with some array to store [type => directive Name ] like this :

array[1]="ng-notify-A";
array[2]="ng-notify-B";
array[3]="ng-notify-C";

I come up to this and don't have idea what's next I can do ... Like I don't know if I can add some logic on directives, or not.

1
  • What's the difference between your directives? I would suggest have only one ng-notify and do some contextual processing depending on the nature of the notify binding Commented Mar 18, 2015 at 0:32

2 Answers 2

1

I don't know if this idea is the best possible solution but it would at least be more DRY.

Create three templates called ng-notify-A.html, ng-notify-B.html, etc. Then do an <ng-include src="notify.type + '.html'">.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it using ngInclude like so:

.constant('tpl_array', {
  '1': 'notify1.tpl.html',
  '2': 'notify2.tpl.html',
  '3': 'notify3.tpl.html'
});

.directive("myNotification", function(tpl_array) {
  return {
    template: '<ng-include src="getTemplateUrl()" />',
    scope: {
      notify: '='
    },
    restrict: 'E',
    controller: function(scope) {
      scope.getTemplateUrl = function() {
        return tpl_array[scope.notify.type];
      };
    }
  };
});

# some.tpl.html
<ul>
  <my-notification ng-repeat="notify in notifies | orderBy: 'id'" notify="notify">
</ul>

# notify1.tpl.html
<li><span ng-notify-A ng-notify="notify"></span></li>

# notify2.tpl.html
<li><span ng-notify-B ng-notify="notify"></span></li>

# notify3.tpl.html
<li><span ng-notify-C ng-notify="notify"></span></li>

1 Comment

can you change the answer to return tpl_array[scope.notify.type]; instead of using switch ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.