从对象中排除 angular ng-change

excluding from an object angular ng-change

大家好,当我启动我的更改功能时,我正在尝试清除我的 ng-model,但我的问题是我不想删除所有我想排除对象中的一项。

function change() {
            if (vm.location.type) {
                angular.forEach(vm.location, function (value, index) {
                    delete vm.location;

                });

            }

        }

所以我不想删除

vm.location.type

我的

vm.location 

              vm.location.boundaries;
              vm.location.region;
              vm.location.address;
              vm.location.name;
              vm.location.nonVisitingRadius;
              vm.location.visitingRadius;

看下面的代码,

var obj = { a:123, b:123, c:123 }
delete obj.a;

因此 obj 将像这样 {b:123, c:123}

Note: Dont need any for loop to delete property from object

更新答案:

var obj= {
  a: 'aaa',
  b: 'bbb',
  c: 'ccc',
  d: 'ddd'
};

var removeObj = function(obj, props) {

    for(var i = 0; i < props.length; i++) {
        if(obj.hasOwnProperty(props[i])) {
            delete obj[props[i]];
        }
    }

};

removeObj (obj, ["a", "d"]);

你可以用一个临时对象来做​​到这一点:

let tempLocation = {};
tempLocation.type = $scope.location.type;
$scope.location = tempLocation;   

我不知道我是否理解正确你在问什么,但如果你想清除对象的所有字段,只保留类型并使用普通 javascirpt(无库)保留对象的引用,遍历字段并检查第 i 个字段是否等于类型。

for(var i in model.location){
if(i !== 'type')
  delete model[i];
}

使用 underscore.js 您可以定义默认模型,例如:

var defaultModel = {
 location: {
   region: '',
   address: '',
   name: '',
   nonVisitingRadius: '',
   visitingRadius: '',
   type: 'defaultvalue'
 }
}

并且在函数内部触发 ng-change 时

_.extend(model, defaultModel);

这将保留类型的默认值并清除所有其他值。