Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


}

});
like image 943
Andres Quintero Avatar asked Sep 29 '16 00:09

Andres Quintero


People also ask

How do I create a new object in TypeScript?

To create an object based on an interface, declare the object's type to be the interface, e.g. const obj1: Employee = {} . The object has to conform to the property names and the type of the values in the interface, otherwise the type checker throws an error.

Can we create object in TypeScript?

Creating standalone objects in typescript: As Fundamentally, Javascript runs with Template-based code snippets, we can create objects directly without creating classes, with taking help of Object Literals and constructor method.

What is an object in angular?

An object is an instance which contains set of key value pairs. The values can be scalar values or functions or even array of other objects.

How do you create a new object in JavaScript?

Creating a JavaScript Object Create a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .


1 Answers

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

like image 186
charlietfl Avatar answered Oct 24 '22 11:10

charlietfl