Search code examples
angularjsangularjs-directiveangularjs-model

Angular directive multiple inputs one model


HTML:

<html ng-app="app">
<div class="container" style="margin-top: 30px">
  <input type="text" ng-model="newName" key-filter/>
  <input type="text" ng-model="newName" key-filter/>
  <input type="text" ng-model="newName" key-filter/>
  <input type="text" ng-model="newName" key-filter/>
</div>
</html>

JS:

var app = angular.module('app', []);
app.directive('keyFilter', function() {
  var pattern = /([\s !$%^&*()_+|~=`{}\[\]:";'<>?,.\/])/;
  function link(scope) {
    scope.$watch('model', function() {
      if(scope.model === undefined)
        return
      if(pattern.test(scope.model)) {
        scope.model = scope.model.replace(pattern, '');
        Materialize.toast('Denied symbol', 4000, 'rounded');
      }
   });
  }
  return {
    restrict: 'A',
    scope: {
      model: '=ngModel'
    },
    link: link
  }
});

I have many inputs which are bind to the same model, and I am filtering user input, when user press a denied key I wanted to show a toast to inform him that he can't use this symbol, but the count of toasts is equal to the count of inputs bind to the same model. I thought i'm working only with model which is one.

Example here: http://codepen.io/anon/pen/XbLjVY?editors=101

How can I fix that, or change the logic how it works

p.s. angular beginner


Solution

  • If they are all bind to the same model every change in one is send to the others, so just put your directive on one input not all of them.

    Here is a working plunkr : http://plnkr.co/edit/dI5TMHms2wsPHc9Xqewf?p=preview

    using :

      <input type="text" ng-model="newName" key-filter/>
      <input type="text" ng-model="newName" />
      <input type="text" ng-model="newName" />
      <input type="text" ng-model="newName" />
    

    You can see in the console the message being displayed only once and from any input field