AngularJS - DRY (input fields, function, directive)

I am new to AngularJS and I got into a situation where my code starts to repeat itself. I'm thinking about creating a new directive, but at the moment I'm a little confused with the scope / isolated controller scope / directive / etc. questions.

This is what I am trying to achieve. Please keep in mind that my code is already working, but without a directive, so I'll put this very theoretically.

I have two entrances, one for the city and one for the zip code.

<input get-zip name="city" ng-model="city" ng-blur="getZip();" />
<input name="zip" ng-model="zip" />

      

When the user enters a city and leaves the input field, the getZip () function (passing param: the value of the city input) must be called, which then searches for the corresponding zip code and enters it into the zip field.

In some situations, we might have two city-zip entries in the same form. In this case, we need to pass the zip input name or model to the call function, so we can add the zip value to the right input.

What would be the correct way to solve this problem? Thank you in advance.

+3


source to share


1 answer


Place zip and city input as directives inside directive. Then you can use many of these pairs in your area.

A directive containing these elements:

(function () {

    angular.module('myApp.directives').directive('cityZipInputPair', function () {
        return {
            restrict: 'E',
            templateUrl: '/Templates/Directives/CityZipInputPair.html',
            scope: {
                city: '=',
                zip: '='
            },
            controller: ['$scope', function ($scope) {
                $scope.getZip = function(){
                    // handle functionality here with $scope.zip and $scope.city
                }

            }]
        }
    });
}).call(this);

      

CityZipInputPair.html should look like this:



<input get-zip name="city" ng-model="city" ng-blur="getZip();" />
<input name="zip" ng-model="zip" />

      

Then the directive can be placed on the page multiple times like this:

<city-zip-input-pair city="city1" zip="zip1"></city-zip-input-pair>
<city-zip-input-pair city="city2" zip="zip2"></city-zip-input-pair>

      

+1


source







All Articles