添加和编辑数据我一直在学习AngularJs最近,并想知道是否有解决以下问题的方法。重新使用HTML表单中Angularjs
我有一个叫cardetails.html页面显示一些汽车的详细信息,如名称,品牌,型号等数据会从看起来在会话存储服务填充。所以,当应用程序第一次运行时,只有“添加”链接可见。单击“添加”将引导用户进入一个名为“CarDetailsForm.html页面包含表单中添加数据。
当提交表单时,数据将被存储在会话存储,用户将被导航回到cardetails.html,赛车的细节将是可见这次与编辑连结。现在,我需要找到一种重用'CarDetailsForm.html'进行编辑的方法。当用户点击编辑链接时,表单应该与表单元素中的填充数据一起打开。我已经完成了大部分工作,但不确定如何正确实施“编辑”功能。我发现下面的链接很有帮助,但我试图避免两次创建相同的表单元素。其他
Angular JS - Edit In Place Content Editing
的一个问题是,当只是一个编辑之后,用户点击浏览器“返回”从cardetails.html为“CarDetailsForm.html”,数据应该仍然存在形式。我怎样才能做到这一点?
而且,我不知道使用自定义指令是否有必要解决这个问题。任何帮助或建议将不胜感激。由于
更新与解决方案代码(刚使用模型绑定)
下面是cardetails.html
<div ng-controller="carDetailsCtrl">
<div>Car Details</div>
<div ng-show="hasData">
<ul>
<li>{{carDetails.name}}</li>
<li>{{carDetails.make}}></li>
</ul>
</div>
<div ng-hide="hasData"><a href="#carDetailsForm">add</a></div>
<div ng-show="hasData"><a href="#carDetailsForm">edit</a></div>
</div>
标记CarDetailsForm.html
<form ng-submit="submit()" ng-controller="carDetailsFormCtrl">
<input type="text" id="name" required="required" ng-model="formData.name">
<input type="text" id="make" required="required" ng-model="formData.make">
<input type="submit" id="submit" value="submit" />
</form>
以下是我的脚本。
app.config([
'$routeProvider', function ($routeProvider) {
$routeProvider.
when('/carDetailsForm', { templateUrl: 'CarDetailsForm.html' }).
//when('/carDetailsForm:carDetails', { templateUrl: 'CarDetailsForm.html' }).
otherwise({
templateUrl: 'cardetails.html'
});
}
]);
app.factory('carDetailsService', function() {
return {
get: function(key) {
return sessionStorage.getItem(key);
},
set: function(key, value) {
sessionStorage.setItem(key, JSON.stringify(value));
},
remove: function(key) {
sessionStorage.removeItem(key);
},
clearAll: function() {
sessionStorage.clear();
}
};
});
app.controller('carDetailsCtrl', ['$scope', 'carDetailsService', function ($scope, carDetailsService) {
var carDetailsInfo = carDetailsService.get("carDetailsInfo");
$scope.carDetails = JSON.parse(carDetailsInfo);
$scope.hasData = false;
if ($scope.carDetails) {
$scope.hasData = true;
}
}]);
app.controller('carDetailsFormCtrl', [
'$scope', 'carDetailsService', '$location', '$routeParams', function($scope, carDetailsService, $location, $routeParams) {
$scope.formData = JSON.parse(carDetailsService.get("carDetailsInfo")) || {} ;
//$scope.formData = $routeParams;
$scope.submit = function() {
carDetailsService.set("carDetailsInfo", $scope.formData);
$location.path('/cardetails');
};
}
]);
感谢。我如何让路线接受一个对象?我应该在$ routeProvider.when(...,{here})中做到这一点吗? – Ren
添加一些示例代码到我的答案 – Claies
我已经解决了这个问题。只需将formData与通过服务从会话存储中检索的数据绑定即可。请参阅上面我更新的代码。我尝试使用$ routeParams,但无法导航到详细信息页面的表单。我在控制台上也找不到任何错误。我评论过我使用过你的方法的地方。如果你能让我知道我在哪里出错了,那会很好。谢谢 – Ren