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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 ?
Yes, you are right, I switched $watch from directive to controller and now it's working as intended, big thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.