2017-03-12 14 views
0

我有角一個指令如下:表內的指導作用不點火

angular 
    .module('accountApp') 
    .directive('matchTo', function() { 
     return { 
      restrict: 'A', 
      require: 'ngModel', 
      link: function(scope, elm, attrs, ctrl) { 

       // var attributes = scope.$eval(attrs.matchTo); 

       ctrl.$validators.matchTo = function(modelValue) { 

        var attributes = scope.$eval(attrs.matchTo); 

        if(attributes.unequal == undefined) { 
         attributes.unequal = false; 
        } 

        console.log(modelValue); 
        console.log(attributes.matchString); 
        console.log(attributes.unequal); 

        if(attributes.unequal) { 
         if(attributes.matchString == undefined || attributes.matchString == null) { 
          return true; 
         } else { 
          return modelValue != attributes.matchString; 
         } 
        } else { 
         if(attributes.matchString == undefined || attributes.matchString == null) { 
          return false; 
         } else { 
          return modelValue == attributes.matchString; 
         }       
        } 
       } 

       scope.$watch(attrs.matchString, function() { 
        ctrl.$validate(); 
        console.log('watch fired'); 
       }); 

      } 
     } 
    }); 

這裏是我的html:只有

<input type="text" id="name" name="name" class="form-control form-input" ng-model="creditDebit.name" 
     ng-disabled="isReadOnly" autocomplete="off" 
     required 
     ng-required-err-type="requiredCreditDebit" /> 

<input type="text" id="code" name="code" class="form-control form-input" ng-model="creditDebit.code" 
     ng-disabled="isReadOnly" autocomplete="off" 
     required 
     match-to="{ matchString: creditDebit.name, unequal: true}" 
     ng-required-err-type="requiredCreditDebitCode" 
     ng-matchTo-err-type="unMatchNameAndCode" /> 

觀看功能火災時,頁面重新加載。但是我希望當價值發生變化時它會被激發。

+0

真正添加到您的手錶功能 –

+0

@Vishal,請參閱解決方案[我的回答(http://stackoverflow.com/a/42745030/2545680) –

回答

1

沒有必要看屬性,因爲它沒有屬性的改變,而是matchString財產的範圍。所以我會這樣做:

var matchTo = $parse(attrs.matchTo); 
scope.$watch(function() { 
    return matchTo(scope).matchString; 
}, function (value) { 
    console.log(value); 
}); 

有關詳細信息,請參閱this plunker

+0

對不起,我的錯誤。它工作正常。謝謝你的回答和你的時間。 – Vishal

+0

@Vishal,當然,不客氣 –

1

您可以使用。

scope.$watch(attrs.matchString, function() { 
       ctrl.$validate(); 
       console.log('watch fired'); 
    },true); 

或嘗試這個現在

element.bind('keypress', function(event) { 
       if(event.keyCode === 32) { 
       event.preventDefault(); 
       } 
      }); 
+0

你剛纔複製我的代碼在第一方塊 – Vishal

+0

沒有你見,真);最後你是否認真? @這些兩個看起來和你一樣? –

+0

對不起,我現在注意到了。但我無法反轉我的投票,因爲它鎖定了。 – Vishal