最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create a new object in angular - Stack Overflow

programmeradmin0浏览0评论

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


}

});

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


}

});
Share Improve this question asked Sep 29, 2016 at 0:59 Andres QuinteroAndres Quintero 2532 gold badges6 silver badges18 bronze badges 1
  • 3 Can you create a sample snippet of your code with HTML. It will be easier to guide you then. – Ajay Narain Mathur Commented Sep 29, 2016 at 1:04
Add a comment  | 

2 Answers 2

Reset to default 10

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

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.

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.

This means we can now simply reset usario to an empty object:

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

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.


Similarly when using $http to send usario we can send the whole object

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.extend()

Try removing this line in your code. usuario=new Object();

You dont need to create another object.

发布评论

评论列表(0)

  1. 暂无评论