angularjs - How to push an object into a json array through $http? -
angularjs - How to push an object into a json array through $http? -
i'm new angularjs. need add together employee file named "employees.json" employee has 3 features, name, city , state can entered through text boxes. current code below , due reason not working. can help me?
$scope.addemplyee=function(){ / create new employee here user inputs // employee object has 3 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 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>
you cannot write file browser. see question : writing json object text file in javascript. however, can send post request server job of writing file.
that beingness said, see several issues in code. name
, city
, state
variables not declared var
(python background?), makes them global although seem meant local.
you have race status on $scope.employees
property : namely, seem rely on fact request finish before post request, there no reason these calls asynchronous. how go wrong? example, $scope.employees
may still not defined when callback of post request executes.
angularjs
Comments
Post a Comment