我的 Controller 中有一个 $scope.model
对象。它的属性在启动时从我的服务器获取,并绑定(bind)到 View 中的输入字段。
<input type="text" ng-model="model.name" placeholder="name"/>
<input type="email" ng-model="model.email" placeholder="email"/>
<!-- ... -->
当我想循环访问来自服务器或表单字段的该模型的所有属性时。例如,我需要它来查找实际更改的属性,以仅将它们发送回服务器。
$scope.save = function() {
// Filter changed properties
var changed = {};
for (i in $scope.model) {
if (i in initial && model[i] == initial[i])
continue;
changed[i] = model[i];
}
// Send them to server
// ...
}
但是,我不知道 AngularJS 是否在内部向我的对象添加属性。那么使用这个语法是否安全,或者我是否会循环遍历一些我不应该看到甚至不应该操作的 AngularJS 特定属性?
最佳答案
Angular 使用 $
为其自己的内容添加前缀,因此如果您想安全,请检查 key 是否以此开头。
例如,如果您使用 ng-repeat
Angular 将添加 $$hashKey
属性。
您永远不会知道他们将来是否会开始添加其他属性,但如果他们这样做,他们(很可能)会遵循他们的约定并为其添加前缀。
$scope.save = function() {
var changed = {};
// Filter changed properties
for (i in $scope.model) {
// Skip Angular prefix
if (i.length && i[0] == '$')
continue;
// Skip if not changed
if (i in initial && model[i] == initial[i])
continue;
// Add to result
changed[i] = model[i];
}
// Send them to server
// ...
}
关于javascript - 我可以在 Angular 模型中使用 for ... in 语法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24301083/