1

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

Octavian Lari
  • 81
  • 2
  • 9

1 Answers1

2

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

ThibaudL
  • 999
  • 9
  • 16
  • Well, it's a nice solution, but I still can't apply it, because all inputs are generated by ng-repeat, it's a complex structure. – Octavian Lari Aug 21 '15 at 11:26
  • 1
    ugly fix : add an hidden input with the directive and let all the others without. otherwise maybe it shouldn't be in a directive ? and just watch your model to add the toast ? – ThibaudL Aug 21 '15 at 11:29
  • Yes, you are right, I switched $watch from directive to controller and now it's working as intended, big thanks! – Octavian Lari Aug 21 '15 at 12:18