Travis Heeter
Travis Heeter

Reputation: 14054

Reusable forms in angular

So I have a form that's basically the same in many different instances, except the names of the inputs may vary, and the data the form represents will be different.

I got a good start on reusable snippets from this post, but I want to expand on that, and figure out how to make it more dynamic.

HTML

<script type='text/ng-template' id="mySnippet"> 
  <form>
    {{mySinppet.firstThing}}<input id="first-input"/>
    {{mySinppet.secondThing}}<input id="second-input"/>
  </form>
</script>
  
<ng-include src="'mySnippet'" ng-model="thingOne"></ng-include>
<ng-include src="'mySnippet'" ng-model="thingTwo"></ng-include>

JS

$scope.thingOne={
  firstThing: "1",
  secondThing: "2",
  foo: src["first-input"],
  bar: src["second-input"],
};
$scope.thingTwo={
  firstThing: "3",
  secondThing: "4",
  first: src["first-input"],
  second: src["second-input"],
};

Here's the plunker for this code (which obviously doesn't work): https://plnkr.co/edit/iCOIq88e7gSSYaE92b0t?p=preview

So how do I set up the snippet/ng-includes to allow communication with a model?

Upvotes: 2

Views: 1041

Answers (1)

gyc
gyc

Reputation: 4360

The answer you linked to is 4 years old. Nobody codes like this anymore. The unaccepted answer though hints at the better solution.

<reusable-form ng-model="thingOne"></reusable-form>
<reusable-form ng-model="thingTwo"></reusable-form>

However there's a limit to how dynamic/reusable you can make a form.

The model you bound to your form should have the same properties.

$scope.thingOne={
  firstThing: "1",
  secondThing: "2"
};
$scope.thingTwo={
  firstThing: "3",
  secondThing: "4"
};

So that the directive is generic enough to be reusable:

  .directive('reusableForm', function() {
    return {
      restrict: 'E',
      scope: {
        ngModel: '='
      },
      template: `
        <input id="first-input" type="text" ng-model="ngModel.firstThing" />
        <input id="second-input" type="text" ng-model="ngModel.secondThing" />
      `
    }
  });

https://plnkr.co/edit/3vrDkrBkA5u6w4hQiW78?p=preview

If you want to make it more dynamic than this, you will end up with spaghetti code and fight with a scope mess.

Upvotes: 4

Related Questions