I have created a directive for common form fields shared across all the forms in a large AngularJS app I am re-factoring.
The app has lots of forms for various data models (user, owners, victims, suppliers, etc). A lot of the forms for these data models contain an address section which is the same format throughout the app.
- Address Line 1
- Address Line 2
- Town / City
- County
- Postcode
- Country
Here is the markup for the directive:
<address-dir
address-line-one="user.address_line_1"
address-line-two="user.address_line_2"
address-town-city="user.address_town_city"
address-county="user.county"
address-postcode="user.postcode"
address-country="user.address_country"
>
</address-dir>
The actual angular directive code is:
(function () {
var app = angular.module('userDirectives', []);
app.directive('addressDir', function () {
return {
restrict: "AE",
require: '^form',
scope: {
addressLineOne: '=',
addressLineTwo: '=',
addressTownCity: '=',
addressCounty: '=',
addressPostcode: '=',
addressCountry: '='
},
templateUrl: 'address.html',
link: function (scope, element, attributes, form) {
scope.addressForm = form;
}
};
});
}());
Here is my address.html template which is the template used in the directive (I have removed all but the first field to simplify the example):
<div>
<label for="address_1">
Address Line 1
</label>
<input
type="text"
id="address_1"
name="address_1"
ng-model="addressLineOne"
required
placeholder="address line 1"
>
<div ng-if="(addressForm.$submitted || addressForm.address_1.$touched)" ng-messages="addressForm.address_1.$error" class="error" role="alert">
<div class="error" ng-message="required">You did not enter first line of address</div>
</div>
</div>
Here's a simple controller:
(function () {
var app = angular.module('userControllers', []);
app.controller('UserController', ['$scope', function ($scope) {
$scope.user = {};
// This is called when the form is sumitted
$scope.continue = function () {
console.log($scope.user);
// save here
};
// get user
User.get().then(function (user) {
$scope.user = user;
});
}]);
}());
I'm working on the project solo for a while and I couldn't find any other directives that do something like this on the net (or at least for common fields in forms).
The reason I have made this a directive instead of a basic include is because I next want to add some custom DOM manipulations to the address section on some of the forms. Probably some third-party address lookup / validation integration.
It is quite basic at moment but I am looking for some external feedback on what I have so far and the direction I'm going in.
addressLineTwo: '=?'
as this is often not required and a consumer of your directive should not have to bind to it. \$\endgroup\$