2016-07-26 47 views
1

我創建了這個數字格式指令,但是如果我在多個輸入上使用它,它並不適用於所有的輸入,但只有一個適用。 任何想法?對於多個元素的角度指令

directive('formatUsNumber', function() { 
    return { 
     restrict: 'A', 
     require: 'ngModel', 
     priority: 100, 
     link: function(scope, element, attrs, ngModel) { 

      scope.formatNumber = function() { 
       var n = element.val(); 
       var dest = n; 
       if (n.length >= 10) { 
        if (/^[A-Za-z\s]+$/.test(n)) { 
         return; 
        } 
        dest = n.replace(/\D/g, ''); 
        if (!isNaN(dest)) { 
         n = dest; 
        } 
        if (n.substr(0, 1) != "1") { 
         n = "1" + n; 
        } 
       } 
       element.val(n); 
       ngModel.$setViewValue(n); 
      }; 
     }, 
    }; 
}); 

模板:

<input type="text" ng-change="formatNumber()" format-us-number ng-model="myModel" /> 

小提琴:http://jsfiddle.net/Lvc0u55v/7479/

回答

1

我想這是因爲指令的範圍不孤立。 而且我也做了一些改變,希望它workes相同

directive('formatUsNumber', function() { 
    return { 
    restrict: 'A', 
    require: 'ngModel', 
    priority: 100, 
      scope: true, 
    link: function(scope, element, attrs, ngModel) { 

     scope.formatNumber = function() { 
      var n = ngModel.$modelValue; 
      if (n.length >= 10) { 
       if (/^[A-Za-z\s]+$/.test(n)) { 
        return; 
       } 
       n = n.replace(/\D/g, ''); 
       if (!isNaN(dest)) { 
        n = dest; 
       } 
       if (n.substr(0, 1) != "1") { 
        n = "1" + n; 
       } 

       ngModel.$setViewValue(n, 'change:directive'); 
      } 
     }; 
    }, 
    }; 
}); 

U可以測試它here

+0

謝謝,它實際上在我的小提琴上工作,但是在我的應用程序中,我得到這個錯誤:'錯誤:[$ compile:multidir]多個指令[formatUsNumber,offClick]要求新/隔離範圍。想法? – Brayan

+0

@Brayan這兩個指令都需要隔離範圍...你能提供offClick指令體嗎?也許我們可以更新它並移除'isolate scope'的用法? – uamanager

+0

@Brayan可以更新'offClick'指令,正如我在他們的git中看到的,他們已經修復了這個問題(https://github.com/TheSharpieOne/angular-off-click/issues/11) – uamanager

1

嘗試增加一個孤立的範圍,這樣的事情:

restrict: 'A', 
require: 'ngModel', 
priority: 100, 
scope:{ 
    ngModel:'=' 
},... 
+0

謝謝,它實際上做了我的小提琴作品,但是在我的應用我得到這個錯誤:'錯誤:[$編譯:multidir]多個指令[formatUsNumber,offClick]尋求新/隔離scope' – Brayan