简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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