Ritesh Gupta Ritesh Gupta - 6 months ago 31
AngularJS Question

How to pass values to Angular JS Service

I have implemented to Edit and Display values on text boxes etc but now want to transfer these code to Angular JS Service.Here is my code-

app.factory('fetchEmpService', ['$rootScope', '$http', function ($rootScope, $http ) {
var employees = [];
return {

editEmp: function (EID) {
debugger;
for (i in $rootScope.employees) {
if ($rootScope.employees[i].EmpId == EID) {
$rootScope.newemployee = {
EmpId: $rootScope.employees[i].EmpId,
Name: $rootScope.employees[i].Name,
Age: $rootScope.employees[i].Age,
City: $rootScope.employees[i].City,
Gender: $rootScope.employees[i].Gender
};
}
}
},


};
}]);


I am using $rootScope instead of $scope (previously used in controller) object. Is it correct way because its returning nothing.

Answer

It's not good practice to store data in $rootScope, you're correct in thinking you need a factory though.

Rather than storing the employees on $rootScope you can store them in the service.

app.factory('fetchEmpService', ['$http', function ($http) {
    var employees = [];

    return {
        getEmployees: function () {
            return employees;
        },
        setEmployees: function (newEmployees) {
            employees = newEmployees;
        },
        editEmp: function (EID) {
            for (var i in employees) {
                if (employees[i].EmpId == EID) {
                    return {
                        EmpId: employees[i].EmpId,
                        Name: employees[i].Name,
                        Age: employees[i].Age,
                        City: employees[i].City,
                        Gender: employees[i].Gender
                    };
                }
            }
        }
    };
}]);

Wherever you initially set $rootScope.employees, change it to fetchEmpService.setEmployees(foo);. To get your employees, fetchEmpService.getEmployees();.

I'm not sure how your editEmp function works so that's up to you to configure, but this is a sensible enough start.

Comments