简体   繁体   English

以角度创建一个新对象

[英]Create a new object in angular

I'm new to programming and I'm having an issue with a memory concept. 我是编程新手,我遇到了内存概念问题。
I have a users page displaying the users in the database through an ng-repeat, and each user has an option to edit or delete. 我有一个用户页面通过ng-repeat显示数据库中的用户,每个用户都有一个编辑或删除选项。 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. 下面是我的代码,当我点击添加新用户时,如何让它创建一个新对象。

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);
        }
        );
    }  


}

});

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. 现在角度ng-model另一个非常有用的部分是你不必为ng-model设置对象的所有属性。 If a property doesn't exist , ng-model will create it. 如果属性不存在, 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发送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 参考

angular.copy() angular.copy()

angular.extend() angular.extend()

Try removing this line in your code. 尝试在代码中删除此行。 usuario=new Object(); usuario = new Object();

You dont need to create another object. 你不需要创建另一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM