在不知道其初始名称的情况下获取AngularJS中的所有ng-model

时间:2017-09-25 11:35:25

标签: javascript angularjs

我知道我们可以检索这样的模型。

<input type="text" name="name" id="firstname" ng-model="firstname" />

在这种情况下,我知道模型名称是firstname。在控制器中,我现在可以使用$scope.firstname访问它。

但是,如果我不知道开发人员在ng-model内定义了哪些模型?

,该怎么办?

我想要的是将所有模型设置在<form>标记内。

对场景的解释很少。

我使用AngularJS进行了对话。对话框的内容可以是任何内容。我目前面临的问题是,当您要提交表单时,提交的值必须在回调函数中返回。

表单的内容可以是任何东西,开发人员决定。所以内容可能如下所示:

<form ng-submit="submit()">
    <strong>Heading</strong>
    <p>Some text content</p>
    <input type="text" ng-model="firstname" name="firstname" />
    <input type="text" ng-model="lastname" name="lastname" />
    <button class="btn" ng-click="cancel()">Cancel</button>
    <button type="submit" class="btn">Submit</button>
</form>

但是,是否可以使用AngularJS获取所有ng-models

(function () {

  angular.module("app", ["dialog"])
  
  .controller("controller", controller);

  function controller($scope, dialog) {
    $scope.openDialog = function () {
      dialog.open({
        template: 'dialog',
        confirm: function (response, scope) {
          console.log(response, scope);
        },
        cancel: function (response, scope) {
            console.log(response, scope);
            scope.close();
        },
        submit: function (response, scope) {
        
        }
      });
    }
  }
  
  angular.module("dialog", [])

    .factory("dialog", function ($rootScope, $http, $injector, $compile, $location, $timeout, $q, $templateCache) {

        // Inject compiler
        $compile = $injector.get('$compile');

        // Shortcut for angular element
        var _ = angular.element;

        // Array with active dialogs
        var dialogs = [];

        // Create a new scope
        var scope = $rootScope.$new();

        // Creates the dialog
        var __construct = {
            new: function (params) {
                var container = _('<div class="dialog-container" />');
                var dialog = _('<dialog />');
                var template = params.template;

                // Throw error if no template has been specified
                if (!template) {
                    console.error("No template given! Create an inline template or create a .html template file.");

                    return;
                }

                // Check if template is an inline template or .html file
                if (template.indexOf('html') !== -1) {
                    template = $http.get(template);

                    template.success(function (template) {
                        __construct.parseTemplate(container, dialog, template);
                    });
                } else {
                
                    var template = $templateCache.get(template);

                    __construct.parseTemplate(container, dialog, template);
                }

                // Set scopes
                __construct.scopes(params)
            },
            /**
             * Appends the template data to the dialog, then appends dialog to the body
             *
             * @param {object}      - Dialog container
             * @param {object}      - Dialog
             * @param {object}      - Template file
             */
            parseTemplate: function (container, dialog, template) {
                // Create DOM data
                dialog.attr("open", "");
                dialog.appendTo(container);
                _(template).appendTo(dialog);
                _('body').append($compile(container)(scope));

                // Push to active dialogs
                dialogs.push(container);
            },
            /**
             * Create scopes and callback functions
             *
             * @param {object}      - Object of given parameters
             */
            scopes: function (params) {
                scope.submit = function () {
                    console.log(scope);
                }
                // Confirm callback
                scope.confirm = function () {

                    // Callback function
                    var confirm = params.confirm;

                    // Returns true
                    return confirm(true, scope);
                },
                // Cancel callback
                scope.cancel = function () {

                    // Callback function
                    var cancel = params.cancel;

                    // Returns true
                    return cancel(false, scope);
                },
                // Close callback
                scope.close = function () {

                    // Destroy the latest dialog inside the dialogs array
                    __destruct.destroy();
                }
            }
        }

        /**
         * Destroys latest dialog.
         * Allways takes the last array item, which has to be the latest dialog.
         */
        var __destruct = {
            destroy: function () {

                // Retrieves and removes last array key
                var dialog = dialogs.pop()

                // Removes the dialog from the document
                _(dialog).remove();
            }
        }

        var __dialog = {
            open: function (params) {            
                __construct.new(params);
            },
            close: function () {

            }
        }

        return __dialog;

    });

})();
/*
    Dialog stylesheet

    @package    ...
    @author     Richard Mauritz
*/

/*
    Match -webkit rules
*/
.dialog-container {
    background: rgba(0, 0, 0, .5);
    position: fixed;
    top: 0;left: 0;
    height: 100%;
    width: 100%;
    z-index: 99999999;
}

dialog {
    position: absolute;
    top: 50%;
    left: 50%;
    right: 0;
    height: auto;
    height: auto;
    height: auto;
    margin: 0;
    border: solid;
    padding: 1em;
    background: white;
    color: black;
    display: block;
    min-width: 350px;
    max-width: 700px;

    -webkit-transform: translate(-50%, -50%);
       -moz-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
}

 /*
    Override with own style
 */
dialog {
    border: 0;
    border-radius: 3px;
}

dialog:before,
dialog:after {
    display: table;
    content: " ";
    clear: both;
}

dialog .btn {
    border: 0;
    padding: 6px 40px !important;
    float: right;
    margin-top: 15px;
    margin-right: 5px;
}

dialog .btn-primary {
    background: none;
    text-transform: uppercase;
    color: #009dff !important;
}

dialog .btn-default {
    background: #f1f1f1;
}

dialog .btn-danger {
    background: #dd4b39;
    color: #fff;
}

dialog .btn-primary:hover,
dialog .btn-primary:focus,
dialog .btn-primary:active,
dialog .btn-primary:active:hover,
dialog .btn-primary:active:focus,
dialog .btn-primary:hover, .btn-primary:focus, 
dialog .btn-primary:focus:hover, 
dialog .btn-primary:active, 
dialog .btn-primary:active:hover {
    background: none;
    color: #009dff;
}

dialog .btn-default:hover,
dialog .btn-default:focus,
dialog .btn-default:active,
dialog .btn-default:active:hover,
dialog .btn-default:active:focus {
    background: #f1f1f1;
}

dialog:not([open]) {
    display: none;
}

dialog + .backdrop {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9999999;
    background: rgba(0,0,0,0.4);
}

._dialog_overlay {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

dialog.fixed {
    position: fixed;
    top: 50%;
    transform: translate(0, -50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="controller">
  
    <button id="open" ng-click="openDialog()">Open dialog</button>
  
    <script type="text/ng-template" id="dialog">
      <form ng-submit="submit()">
        <strong>Warning</strong>
        <p>Fill in your firstname and lastname</p>
        <input type="text" ng-model="firstname" name="firstname" />
        <input type="text" ng-model="lastname" name="lastname" />
        <button class="btn" ng-click="cancel()">Cancel</button>
        <button type="submit" class="btn">Submit</button>
      </form>
    </script>
  
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

  

这个stackoverflow.com/a/36073750/5621827 - jitender

怎么样?

我根据@jitender

发布的链接编写了一个解决方案

我希望开发人员可以自由使用文字,名称,对象等。

提交功能现在有以下代码:

scope.submit = function () {
    // Callback function
    var submit = params.submit;

    // Get current dialog
    // Every newly created dialog will be pushed to the dialogs array
    // Code below gets the last array item
    var dialog = dialogs[dialogs.length - 1]; 

    // Array which will store the form data
    var formValues = [];
    // Get form by name
    var formName = _(dialog).find("form").attr("name");
    // Get form scope
    var formScope = scope[formName];

    // Get form elements
    angular.forEach(formScope, function (element, name) {
        if (!name.startsWith('$')) {
            var obj = {};
            obj[name] = scope[name];

            // Store into formValues
            formValues.push(obj);
        }
    });

    return submit(formValues, scope);
}

工作演示

(function () {

  angular.module("app", ["dialog"])
  
  .controller("controller", controller);

  function controller($scope, dialog) {
    $scope.openDialog = function () {
      dialog.open({
        template: 'dialog',
        confirm: function (response, scope) {
          console.log(response, scope);
        },
        cancel: function (response, scope) {
            console.log(response, scope);
            scope.close();
        },
        submit: function (response, scope) {
            console.log(response);
        }
      });
    }
  }
  
  angular.module("dialog", [])

    .factory("dialog", function ($rootScope, $http, $injector, $compile, $location, $timeout, $q, $templateCache) {

        // Inject compiler
        $compile = $injector.get('$compile');

        // Shortcut for angular element
        var _ = angular.element;

        // Array with active dialogs
        var dialogs = [];

        // Create a new scope
        var scope = $rootScope.$new();

        // Creates the dialog
        var __construct = {
            new: function (params) {
                var container = _('<div class="dialog-container" />');
                var dialog = _('<dialog />');
                var template = params.template;

                // Throw error if no template has been specified
                if (!template) {
                    console.error("No template given! Create an inline template or create a .html template file.");

                    return;
                }

                // Check if template is an inline template or .html file
                if (template.indexOf('html') !== -1) {
                    template = $http.get(template);

                    template.success(function (template) {
                        __construct.parseTemplate(container, dialog, template);
                    });
                } else {
                
                    var template = $templateCache.get(template);

                    __construct.parseTemplate(container, dialog, template);
                }

                // Set scopes
                __construct.scopes(params)
            },
            /**
             * Appends the template data to the dialog, then appends dialog to the body
             *
             * @param {object}      - Dialog container
             * @param {object}      - Dialog
             * @param {object}      - Template file
             */
            parseTemplate: function (container, dialog, template) {
                // Create DOM data
                dialog.attr("open", "");
                dialog.appendTo(container);
                _(template).appendTo(dialog);
                _('body').append($compile(container)(scope));

                // Push to active dialogs
                dialogs.push(container);
            },
            /**
             * Create scopes and callback functions
             *
             * @param {object}      - Object of given parameters
             */
            scopes: function (params) {
                // Submit callback
                scope.submit = function () {
                    // Callback function
                    var submit = params.submit;

                    // Get current dialog
                    var dialog = dialogs[dialogs.length - 1];

                    // Get form scope by name
                    var formValues = [];
                    var formName = _(dialog).find("form").attr("name");
                    var formScope = scope[formName];

                    // Get form elements
                    angular.forEach(formScope, function (element, name) {
                        if (!name.startsWith('$')) {
                            var obj = {};
                            obj[name] = scope[name];

                            formValues.push(obj);
                        }
                    });

                    return submit(formValues, scope);
                }
                // Confirm callback
                scope.confirm = function () {

                    // Callback function
                    var confirm = params.confirm;

                    // Returns true
                    return confirm(true, scope);
                },
                // Cancel callback
                scope.cancel = function () {

                    // Callback function
                    var cancel = params.cancel;

                    // Returns true
                    return cancel(false, scope);
                },
                // Close callback
                scope.close = function () {

                    // Destroy the latest dialog inside the dialogs array
                    __destruct.destroy();
                }
            }
        }

        /**
         * Destroys latest dialog.
         * Allways takes the last array item, which has to be the latest dialog.
         */
        var __destruct = {
            destroy: function () {

                // Retrieves and removes last array key
                var dialog = dialogs.pop()

                // Removes the dialog from the document
                _(dialog).remove();
            }
        }

        var __dialog = {
            open: function (params) {            
                __construct.new(params);
            },
            close: function () {

            }
        }

        return __dialog;

    });

})();
/*
    Dialog stylesheet

    @package    ...
    @author     Richard Mauritz
*/

/*
    Match -webkit rules
*/
.dialog-container {
    background: rgba(0, 0, 0, .5);
    position: fixed;
    top: 0;left: 0;
    height: 100%;
    width: 100%;
    z-index: 99999999;
}

dialog {
    position: absolute;
    top: 50%;
    left: 50%;
    right: 0;
    height: auto;
    height: auto;
    height: auto;
    margin: 0;
    border: solid;
    padding: 1em;
    background: white;
    color: black;
    display: block;
    min-width: 350px;
    max-width: 700px;

    -webkit-transform: translate(-50%, -50%);
       -moz-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
}

 /*
    Override with own style
 */
dialog {
    border: 0;
    border-radius: 3px;
}

dialog:before,
dialog:after {
    display: table;
    content: " ";
    clear: both;
}

dialog .btn {
    border: 0;
    padding: 6px 40px !important;
    float: right;
    margin-top: 15px;
    margin-right: 5px;
}

dialog .btn-primary {
    background: none;
    text-transform: uppercase;
    color: #009dff !important;
}

dialog .btn-default {
    background: #f1f1f1;
}

dialog .btn-danger {
    background: #dd4b39;
    color: #fff;
}

dialog .btn-primary:hover,
dialog .btn-primary:focus,
dialog .btn-primary:active,
dialog .btn-primary:active:hover,
dialog .btn-primary:active:focus,
dialog .btn-primary:hover, .btn-primary:focus, 
dialog .btn-primary:focus:hover, 
dialog .btn-primary:active, 
dialog .btn-primary:active:hover {
    background: none;
    color: #009dff;
}

dialog .btn-default:hover,
dialog .btn-default:focus,
dialog .btn-default:active,
dialog .btn-default:active:hover,
dialog .btn-default:active:focus {
    background: #f1f1f1;
}

dialog:not([open]) {
    display: none;
}

dialog + .backdrop {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9999999;
    background: rgba(0,0,0,0.4);
}

._dialog_overlay {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

dialog.fixed {
    position: fixed;
    top: 50%;
    transform: translate(0, -50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="controller">
  
    <button id="open" ng-click="openDialog()">Open dialog</button>
  
    <script type="text/ng-template" id="dialog">
      <form ng-submit="submit()" name="testForm">
        <strong>Warning</strong>
        <p>Fill in your firstname and lastname</p>
        <input type="text" ng-model="firstname" name="firstname" />
        <input type="text" ng-model="lastname" name="lastname" />
        <button class="btn" ng-click="cancel()">Cancel</button>
        <button type="submit" class="btn">Submit</button>
      </form>
    </script>
  
  </div>
</div>

答案 1 :(得分:1)

我不确定我是否清楚地理解了您的问题,但是,听起来您正试图访问由提交表单输入创建的模型。 我通常会做以下事情:

<div class="form-group">
      <label class="col-md-3 control-label">Company Title:
      <span class="required" aria-required="true"> * </span></label>
      <div class="col-md-4">
        <input type="text" ng-model="reg.company_title" name="company_title" class="form-control" ng-class="{'has-error': ng-invalid}"
          ng-required="true">
        <span class="help-block"> This is the name customers will see online. </span>
      </div>
      <div ng-messages="registrationForm.company_title.$error" ng-if="registrationForm.company_title.$dirty">
        <span ng-message="required" class="registration-error">This field is required.</span>
      </div>
</div>

这可能比您需要看到的要多一点,但我确实只是从项目中复制它,而且我懒得删除额外的东西。

正如您所看到的,我的ng-model表示&#39; registration.company_title&#39;。这允许我从控制器访问$ scope.registration.company_title。角度文档就是我所说here

的一个很好的例子

此外,您可以在行动here中看到整个表单。

因此,如果您要在控制器中访问一组输入字段,请将它们设置为上述对象上的字段。希望有所帮助!