Luke Berry
Luke Berry

Reputation: 1947

Share data between directives

I'm rendering a large form that is described in a json file, in my view I'm using ng-repeat and then sending each element to a 'master' directive called FormRender, I have a controller in this directive that is switching on obj.QuestionType. I then want to be able to send that object to a different directive based on its type, for example if it is a multiple choice question I want to be able to send it to multipleRender and then have that load the correct partial view with the data inside.

So far I'm not entirely sure how to do this, questions are described in the following format.

{
  "QuestionID": 1,
  "QuestionPage": 1,
  "QuestionName": "CurrentFirms",
  "QuestionType": "text",
  "QuestionLabel": "Current Firm(s)",
},

I'm rendering it like so

 <form action="" method="POST">
      <fieldset ng-repeat='item in data[0]'>
        <form-render obj='item'></form-render>

The formRender directive looks like this

.directive('formRender', function() {
  return {
    restrict: 'E',
    scope: { obj: '=' },
    controller: function($scope) {
      var type = $scope.obj.QuestionType;
      switch(type) {
        case 'multiple':
            // send this to a different directive to handle and render
          break;
      }
    }
  };

What's the best way to move forward?

Cheers,

Upvotes: 0

Views: 141

Answers (1)

Robin Elvin
Robin Elvin

Reputation: 1255

I would use ngSwitch - AngularJS ngSwitch documentation - and select the directive in the template.

<form action="" method="POST">
   <fieldset ng-repeat='item in data[0]' ng-switch on="item.QuestionType">
      <my-form-text-directive ng-switch-when="text" obj="item"></my-form-text-directive>
      <my-form-multiple-directive ng-switch-when="multiple" obj="item"></my-form-multiple-directive>
   <fieldset>
</form>

Upvotes: 1

Related Questions