2013-07-25 161 views
0

我已經知道如何檢查表單上的某些輸入元素是否髒,但我想知道是否有一個快速的方法來只遍歷$ dirty的元素?我知道Angular在元素上設置了一個ng-dirty類,我可以弄清楚如何在jQuery中做到這一點,但我無法弄清楚如何在AngularJS上下文中做到這一點。

+0

看到它在行動你在尋找的東西就像一個過濾器? – MBielski

+0

因此,您可以通過在自定義指令中抓取NgFormController的實例來完成此操作。但是,真正的問題是,如果你想迭代這些元素?什麼是你的功能用例? –

+0

大型表單預先填充了數據。我想通過$ http POST發送更新的字段。 – Photovor

回答

3

我寫了一個過濾器(來自社區的一些幫助)做了一段時間後,它給了我很好的服務。

/* App Module */ 
angular.module("dirtyFilter", []). 
filter("returnDirtyItems", function() {   
return function (modelToFilter, form, treatAsDirty, removeTheseCharacters) { 
    //removes pristine items 
    //note: treatAsDirty must be an array containing the names of items that should not be removed 
    for (var key in modelToFilter) { 
     //delete the item if: 
     // * it exists on the form and is pristine, or... 
     // * does not exist on the form 
     try{ 
      //console.log("checking " + key + " for pristine and found it is " + form[key].$pristine); 
     } 
     catch(err){ 
      //console.log("key " + key + " did not have an element in the form"); 
     } 
     if (removeTheseCharacters != undefined && removeTheseCharacters.length > 0) { 
      for (var CA = 0, len = removeTheseCharacters.length; CA < len; CA++) { 
       try{ 
        //console.log("Index of " + key + " is: " + modelToFilter[key].indexOf(removeTheseCharacters[CA])); 
        if (modelToFilter[key].indexOf(removeTheseCharacters[CA]) >= 0) { 
         modelToFilter[key] = modelToFilter[key].replace(removeTheseCharacters[CA], "", "g"); 
        } 
       } 
       catch(err){ 
        //console.log("getting the index of " + key + " throws an error of " + err + " so we skipped it"); 
       } 
      } 
     } 
     if ((form[key] && form[key].$pristine) || !form[key]) { 
      //delete the item if the treatAsDirty argument is not present 
      //console.log("Checking to see if " + key + " is to be treated as always dirty"); 
      if(treatAsDirty){ 
       //console.log("There is an array present for treatAsDirty"); 
       //delete the item if it is not in the treatAsDirty array 
       if(treatAsDirty.indexOf(key) == -1){ 
        //console.log("The item " + key + " was not found in the always dirty array and has been deleted"); 
        //remove the pristine item from the parent object 
        delete modelToFilter[key]; 
       } else { 
        //console.log("The item " + key + " was found in the always dirty array and has been kept"); 
       } 
      } else { 
       //console.log("There is no array present for dirty items, so " + key + " will be removed"); 
       //remove the pristine item from the parent object 
       delete modelToFilter[key]; 
      } 
     } 
    } 
    return modelToFilter; 
} 
}); 

您可以在http://jsfiddle.net/mbielski/sdN2h/1/

+0

完美工作。謝謝! – Photovor