添加和編輯數據我一直在學習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