AngularJS - DRY (input fields, function, directive) -


i new angularjs , got in situation code starts repeat. thinking of creating new directive bit confused scope/isolated scope/directive's controller/etc. issues.

here trying achieve. please have in mind code working without directive, put in theoretic way.

i have 2 inputs, 1 city , 1 zip code.

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

when user enters city , leaves input field, function getzip() should called (passing param: value of city input) searches corresponded zip code , enters zip field.

in situations have 2 city-zip inputs on same form. in case need pass zip input name or model calling function, can append zip value right input.

what right way solve issue? thank in advance.

put zip , city inputs directives inside directive. can have many of these pairs each own scope.

the 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 $scope.zip , $scope.city                 }              }]         }     }); }).call(this); 

cityzipinputpair.html should like:

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

the directive can put onto page multiple times follows:

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

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -