Javascript 以角度创建一个新对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39759760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a new object in angular
提问by Andres Quintero
I'm new to programming and I'm having an issue with a memory concept.
I have a userspage displaying the users in the database through an ng-repeat, and each user has an option to edit or delete.
I also have a button on that page to add a new user. My issue is that when I edit a user, the information for that user remains in memory. Therefore; when I click new, the fields populate with the latest user I edited.
Below is my code, how can I make it create a new object when I click to add a new user.
我是编程新手,并且在内存概念方面遇到了问题。
我有一个用户页面,通过 ng-repeat 显示数据库中的用户,每个用户都可以选择编辑或删除。我在该页面上还有一个按钮来添加新用户。我的问题是,当我编辑用户时,该用户的信息会保留在内存中。所以; 当我单击新建时,这些字段会填充我编辑过的最新用户。下面是我的代码,当我单击添加新用户时,如何让它创建一个新对象。
var app = angular.module("dico", []);
app.service('srvUsuarios', function($http){
var usuarios = [];
var usuario = {"id":"","fullname":"","username":"","password":"", "role_id":"","email":""};
this.getusuarios = function(){
return usuarios;
};
this.getusuario = function(){
return usuario;
};
this.nuevo = function(){
usuario=new Object();
usuario.id = "";
usuario.fullname = "";
usuario.username = "";
usuario.password = "";
usuario.role_id = "";
usuario.email = "";
};
this.editar = function(usuarioEditar){
//usuario=new Object();
//console.log(usuario);
usuario.id = usuarioEditar.id;
usuario.fullname = usuarioEditar.fullname;
usuario.username = usuarioEditar.username;
usuario.password = usuarioEditar.password;
usuario.role_descripcion = usuarioEditar.role_descripcion;
usuario.email = usuarioEditar.email;
console.log(usuario);
};
});
app.controller("usuarios", function($scope,$http, srvUsuarios){
$scope.usuarios = srvUsuarios.getusuarios();
console.log($scope.usuarios);
$scope.usuario = srvUsuarios.getusuario();
console.log($scope.usuario);
$http.get(ROOT+'usuarios/listar').then(
function(response){
$scope.usuarios = response.data;
$scope.usuarios.push($scope.usuario);
console.log($scope.usuarios);
}, function errorCallback(response){
console.log("Error", response);
});
$scope.filaLimite = 100;
$scope.sortColumn = "name";
$scope.reverseSort = false;
$scope.sortData = function(column){
$scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
$scope.sortColumn = column;
}
$scope.getSortClass = function(column){
if($scope.sortColumn == column){
return $scope.reverseSort ? "arrow-down" : "arrow-up";
}
return "";
}
$scope.nuevo = function(){
srvUsuarios.nuevo();
}
$scope.editar = function(usuario){
srvUsuarios.editar(usuario);
}
$scope.eliminar = function(usuario){
var index = $scope.usuarios.indexOf(usuario);
if (index > -1){
$http.post(ROOT+'/usuarios/eliminar',{id:usuario.id}).then(
function(response){
if (response.data="true"){
$scope.usuarios.splice(index, 1);
}
},function errorCallback(response){
console.log("Error", response);
}
);
}
}
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
$scope.show = function(id){
if(id == ""){
$scope.mostrar = "0";
console.log($scope.mostrar)
}
else{
$scope.mostrar = "1";
}
}
});
app.controller("usuario", function($scope, $http, srvUsuarios){
$scope.usuario = srvUsuarios.getusuario();
$scope.usuarios = srvUsuarios.getusuarios();
$scope.accion = function(id){
if(id == ""){
return "Nuevo";
}
else{
return "Editar";
}
}
$scope.guardar = function(usuario){
if(usuario.id == ""){
$http.post(ROOT+'usuarios/insertar',{
'fullname':usuario.fullname,
'username':usuario.username,
'email':usuario.email})
.then(function(response){
console.log(response);
location.reload(true);
},function errorCallback(response){
console.log("Error", response);
}
);
}else{
console.clear();
console.log($scope.usuarios);
$http.post(ROOT+'usuarios/editar',{'id':usuario.id,
'fullname':usuario.fullname,
'email':usuario.email})
.then(function(response){
console.log( usuario.id);
location.reload(true);
},function errorCallback(response){
console.log($scope.usuarios);
console.log("Error", response.data);
}
);
}
}
});
回答by charlietfl
Some fundamentals and simplifications.
一些基本原理和简化。
When you push an object to an array it does not make a copy of the object..it is a reference to that object. This is a critical concept to understand in javascript and fundamental to a lot of working with angular
当您将对象推送到数组时,它不会制作对象的副本......它是对该对象的引用。这是在 javascript 中理解的一个关键概念,也是大量使用 angular 的基础
Editing the same object after pushing it to array will edit both instances since they are both references to the exact same object. This is probably your "memory"problem.
将同一个对象推送到数组后编辑它会同时编辑两个实例,因为它们都是对完全相同对象的引用。这可能是您的“记忆”问题。
We can use angular.copy()
to assist there.
我们可以angular.copy()
用来协助那里。
usuarios.push(angular.copy(usario));
Now another very helpful part of angular ng-model
is you don't have to set all the properties of an object for ng-model
to work. If a property doesn't exist , ng-model
will create it.
现在 angular 的另一个非常有用的部分ng-model
是您不必设置对象的所有属性ng-model
即可工作。如果属性不存在,ng-model
将创建它。
This means we can now simply reset usario to an empty object:
这意味着我们现在可以简单地将 usario 重置为一个空对象:
usario = {};
then edit this object in the form and when complete and validated in form push a new copy to the array and reset it again
然后在表单中编辑此对象,并在完成并在表单中验证后将新副本推送到数组并再次重置
Now if you want to edit an existing user you don't have to manually copy all the values of each property to usario
we can use angular.extend()
to do that for us
现在,如果您想编辑现有用户,则不必手动复制每个属性的所有值,usario
我们可以使用它angular.extend()
来为我们执行此操作
this.editar = function(usuarioEditar){
angular.extend(usario, usuarioEditar);
}
Now all the properties of usuarioEditar
have been used to overwrite the properties of usario
or create them if they weren't there.
现在,如果它们不存在,则所有的属性usuarioEditar
都已被用于覆盖usario
或创建它们的属性。
Similarly when using $http
to send usario
we can send the whole object
同样,当使用$http
to send 时,usario
我们可以发送整个对象
if(usuario.id == ""){
var postData = angular.copy(usario)
delete data.id;
$http.post(ROOT+'usuarios/insertar', postData ).then(...
As you can see this will significantly streamline all the object handling and cut down a lot of time and code.
如您所见,这将显着简化所有对象处理并减少大量时间和代码。
Hopefully this answers some of your questions and helps you going forward
希望这能回答您的一些问题并帮助您继续前进
References
参考
回答by Ganesh Hegde
Try removing this line in your code. usuario=new Object();
尝试删除代码中的这一行。usuario=新对象();
You dont need to create another object.
您不需要创建另一个对象。