AngularJS迭代$ dirty元素

时间:2013-07-25 17:07:37

标签: angularjs

我已经知道如何检查我的表单上的某些输入元素是否脏了,但我想知道是否有一种快速的方法来仅仅迭代$脏的?我知道Angular在元素上设置了一个ng-dirty类,我可以弄清楚如何在jQuery中执行此操作,但我无法弄清楚如何在AngularJS上下文中执行此操作。

1 个答案:

答案 0 :(得分: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/

看到它的实际效果