使用angularjs中的sessionStorage在输入数据时进行自动保存

时间:2018-05-03 11:34:21

标签: angularjs

我正在使用sessionStorage自动保存表单数据,同时将数据输入到输入字段中。但是我无法保存数据。如果刷新页面,则数据应出现在输入字段中。谁能解释为什么它不起作用?

我的表格是,

<form name="createArticleForm" ng-change="autoSave()">
<input type="text" name="firstname" ng-model="emp.firstname" required>
<input type="text" name="lastname" ng-model="emp.lastname" required>
<input type="text" name="designation" ng-model="emp.designation" required>
</form>

Js文件:

$scope.autoSave= function(){
$scope.emp={};
sessionStorage.setItem('emp', JSON.stringify(emp));
var save = JSON.parse(sessionStorage.emp);
console.log(sessionStorage['emp']);
}

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
  <p>Write something in the input field:</p>
  <input type="text" ng-model="emp.firstname" ng-change="myFunc()" ng-model="myValue" />
  <input type="text" ng-model="emp.lastname" ng-change="myFunc()" ng-model="myValue" />
  <input type="text" ng-model="emp.email" ng-change="myFunc()" ng-model="myValue" />
  <input type="text" ng-model="emp.password" ng-change="myFunc()" ng-model="myValue" />
  <p>The input field has changed {{value}} times.</p>

</div>

<script>
  angular.module('myApp', [])
    .controller('myCtrl', ['$scope', function($scope) {
      $scope.myFunc = function() {
        sessionStorage.setItem('emp', JSON.stringify($scope.emp));
        $scope.value = JSON.parse(sessionStorage.getItem('emp'))
      };
    }]);
</script>
</body>
</html>
&#13;
&#13;
&#13;