javascript 重用 html 表单在 Angularjs 中添加和编辑数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22076289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:22:40  来源:igfitidea点击:

Reusing a html form to add and edit data in Angularjs

javascripthtmlangularjs

提问by Ren

I've been learning AngularJs recently, and was wondering if there is a way to solve the below problem.

我最近一直在学习 AngularJs,想知道是否有办法解决以下问题。

I have a page called cardetails.html that displays some car details such as name, make, model etc. The data gets populated from a service that looks upon the session storage. So, when the app is run for the first time, only the 'add' link is visible. Clicking on 'add' will navigate the user to a page called 'CarDetailsForm.html' that contains the form to add data.

我有一个名为 cardtails.html 的页面,它显示一些汽车详细信息,例如名称、品牌、型号等。数据是从查看会话存储的服务中填充的。因此,当应用程序第一次运行时,只有“添加”链接可见。单击“添加”会将用户导航到名为“CarDetailsForm.html”的页面,该页面包含要添加数据的表单。

When the form is submitted, data will be stored in session storage and the user will be navigated back to the cardetails.html, and the car details will be visible this time along with the edit link. Now, I need to find a way to reuse 'CarDetailsForm.html' for editing as well. When, the user clicks on edit link, the form should open along with the populated data in form elements. I have done most of the work, but not sure about how to implement 'Edit' feature properly. I found the below link helpful, but I'm trying to avoid creating the same form elements twice.

提交表单后,数据将存储在会话存储中,用户将被导航回 cardtails.html,这次将可以看到汽车详细信息以及编辑链接。现在,我还需要找到一种方法来重用“CarDetailsForm.html”进行编辑。当用户单击编辑链接时,表单应与表单元素中的填充数据一起打开。我已经完成了大部分工作,但不确定如何正确实现“编辑”功能。我发现下面的链接很有帮助,但我试图避免创建相同的表单元素两次。

Angular JS - Edit In Place Content Editing

Angular JS - 就地编辑内容编辑

One other issue is that when the user hits 'back' on the browser from cardetails.html to 'CarDetailsForm.html' just after an edit, the data should still persist on the form. How can I achieve this ?

另一个问题是,当用户在编辑后立即在浏览器上点击“返回”从 cardtails.html 到“CarDetailsForm.html”时,数据仍应保留在表单上。我怎样才能做到这一点?

Also, i'm not sure whether using custom directives is necessary to solve this problem. Any help or advice would be much appreciated. Thanks

另外,我不确定是否需要使用自定义指令来解决这个问题。任何帮助或建议将不胜感激。谢谢

Updated the code with the solution(just had to use model binding)

用解决方案更新了代码(只需要使用模型绑定)

Below is the markup for cardetails.html

下面是 cardtails.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

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>

Below are my scripts.

下面是我的脚本。

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');
        };
    }
]);

回答by Claies

Instead of having two unique routes that load the same templateUrl, you should have one route which accepts a carDetailsInfoobject and binds it to the form, but has an empty object as the default. Then you call the same route for both button actions, passing in your object for the edit but not passing it for the new.

与其有两个加载相同 templateUrl 的唯一路由,您应该有一个接受carDetailsInfo对象并将其绑定到表单的路由,但默认有一个空对象。然后,您为两个按钮操作调用相同的路由,将您的对象传递给编辑,但不将其传递给新的。

sample code to handle passing data:

处理传递数据的示例代码:

$routeProvider.
        when('/editCarDetails:carDetailsInfo', { templateUrl: 'CarDetailsForm.html' })

app.controller('carDetailsFormCtrl', [
'$scope', 'carDetailsService', '$routeParams', '$location', 
           function($scope, carDetailsService, $routeParams, $location) {

$scope.formData = $routeParams;

from Angular Docs

来自Angular 文档