簡體   English   中英

角度指令多輸入一個模型

[英]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
  }
});

我有許多綁定到同一模型的輸入,並且我正在過濾用戶輸入,當用戶按下拒絕鍵時,我想向祝酒詞表示他不能使用此符號,但是祝酒詞的數量是相等的輸入的數量綁定到同一模型。 我以為我只使用模型之一。

此處的示例: http : //codepen.io/anon/pen/XbLjVY?editors=101

我該如何解決,或更改其工作原理

ps角初學者

如果它們都綁定到同一模型,則一個更改中的每個更改都會發送給其他模型,因此只需將指令放在一個輸入上,而不是全部。

這是一個工作正常的plunkr: http ://plnkr.co/edit/dI5TMHms2wsPHc9Xqewf?p=preview

使用:

  <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" />

您可以在控制台中看到該消息僅在任何輸入字段中顯示一次

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM