What is the proper way to use factory in controller

时间:2016-08-31 12:08:21

标签: angularjs

I want to write emphasis code only once. How can I achieve that? On submit, I want to perform to task

  1. To save data in Database
  2. Render the submitted data on UI

Code

    .controller("myController", function ($scope, $http, getDataService) {
        $scope.submit = function () {
            var Employee = { "empID": $scope.empId, "Name":   $scope.empName, "Gender": $scope.empGender }
            $http(
          {
              method: 'POST',
              url: 'http://localhost:58365/home/saveEmpData',
              data: { emp: Employee },
              headers: { 'Content-Type': 'application/JSON;  charset=UTF-8' }
          }).then(function (response) {
              $scope.data123 = response.data;
          });

            **getDataService.fetchuserDetails().then(function (response)
            { $scope.data1 = response.data; });**
        }

        **getDataService.fetchuserDetails().then(function (response)
        { $scope.data1 = response.data; });**  

         }) 

Factory

        .factory("getDataService", ['$http', function ($http) {
            var obj = {};
            obj.fetchuserDetails = function ()
            {
                return $http.get('http://localhost:58365/home/GetEmpData');
            }

            return obj;
        }])

1 个答案:

答案 0 :(得分:0)

To Save data in database,

$scope.saveData = function (xyz) {
   getDataService.save(xyz, function () {

      // write action you want to perform after saving your data

   })
}; 

Call saveData( ) method in HTML and pass the variable where you are getting data or the variable where you are going to store temporary data.

To render submitted data it's better to write another controller.
Then run .query() method or .get() and collect it in one $scope variable.

相关问题