Zach Zach - 5 months ago 17
AngularJS Question

Is it possible to put an entire form into ONE AngularJs directive?

I have seen many examples of people using a combination of HTML and directives to create an AngularJS form (like here), but I am trying to create a standalone widget, that has all of the HTML for the form in the templateURL field of the directive, so I can just insert this one line directive anywhere into another HTML file and have a form. Any suggestions?

Answer

Here is a plnkr with directive examples that bring the form and an update button/callback as an example.

I define my directive like this; I used template when the form is simple:

angular.module('components', [])
  .directive('myForm', function() {
    return {
      restrict: 'E',
      template: `<form novalidate class="simple-form">
    Name: <input type="text" ng-model="user.name" /><br />
    E-mail: <input type="email" ng-model="user.email" /><br />
    <input type="submit" ng-click="update(user)" value="Save" />
  </form>`,
      link: function(scope, element, attr) {
        scope.update = function(user) {
          console.log('update ' + JSON.stringify(user));
        }
      }

    }
  });

So, the directive brings the form and I defined a function 'update' that I have call on the submit button. The function displays a message in the console... for instance:

update {"name":"john doe","email":"john@doe.doe"}

The rest of the app has nothing:

angular.module('HelloApp', ['components'])
  .controller('MyCtrl', ['$scope', function($scope) {
    $scope.name = 'This is the controller';
  }]);

And the HTML looks like this:

<body>
  <div ng-controller="MyCtrl">
    <my-form></my-form>
  </div>
</body>

If you want to use templateUrl instead, I have another directive defined like this:

  .directive('myFormExternal', function() {
    return {
      restrict: 'E',
      templateUrl: 'myFormExternal.html',
      link: function(scope, element, attr) {
        scope.updateExternal = function(user) {
          console.log('External Form: ' + JSON.stringify(user));
        }
      }

    }
  });

And the form html is:

<form novalidate class="simple-form">
    Firstname: <input type="text" ng-model="external.firstname" /><br />
    Lastname: <input type="text" ng-model="external.lastname" /><br />
    <input type="submit" ng-click="updateExternal(external)" value="Save" />
  </form>

Hope this helps. Let us know.

Comments