0

I'm new to angularJS. What I need to do is to add an employee into a file named as "employees.json" where an employee has 3 features, name, city and state which can be entered through text boxes. My current code is below and due to some reason it is not working. Can someone help me?

    $scope.addEmplyee=function(){
        / create new employee here with user inputs 
        // an Employee object has three properties: name, city, state 
        var name=$scope.name;
        var city=$scope.city;
        var state=$scope.state;

        $http.get('employees.json').success(function (data){
           $scope.employees = data});

        $scope.employee={"name":name,"city":city,"state":state};

        $http.post('/employees.json', {"employee": $scope.employee})
           .success(function(response,  status, headers, config){
              $scope.employees.push($scope.employee);
        });


    };

HTML code is as follows

     <div>
        <b>Add Employee :</b>
        <div>Name:<input type="text" ng-model="name"/></div>
        <div>City: <input type="text" ng-model="city"/></div>
        <div>State: <input type="text" ng-model="state"/></div>
        <button class="btn" ng-click="addEmplyee()">Add</button>
    </div>
New Dev
  • 48,427
  • 12
  • 87
  • 129

1 Answers1

0

You cannot really write to a file from the browser. See this question : Writing a json object to a text file in javascript. However, you can send the POST request to a server who will do the job of writing to the file.

That being said, I see several issues in your code. Your name, city and state variables are not declared with var (Python background?), which makes them global although they seem meant to be local.

You have a race condition on your $scope.employees property : namely, you seem to rely on the fact that the GET request will complete before the POST request, but there is no reason for that as these calls are asynchronous. How could it go wrong? For example, $scope.employees may well still not be defined when the callback of the POST request executes.

Community
  • 1
  • 1
Valentin Waeselynck
  • 5,950
  • 26
  • 43