【问题标题】:How to include the value of a clicked button in a separate form with AngularJS如何使用 AngularJS 在单独的表单中包含单击按钮的值
【发布时间】:2015-02-15 23:17:15
【问题描述】:

我正在使用 ui-router 在带有 AngularJS 的页面上显示两个视图。底部视图是可供选择的产品列表。页面上的顶视图是一个表单,显示供用户在选择每个项目后完成。我希望表单在最终提交时包含所选项目的值。这两个视图当前使用单独的控制器。

据我了解,AngularJS 不使用隐藏字段。将表单与所选项目相关联以便在提交时将其包含在内的最佳方法是什么?理想情况下,我想在用户单击“选择”按钮后立即将选择类型绑定到表单。

HTML:

<!--Form HTML-->

<form name="myForm">
<div class="control-group">
    <label>Name</label>
    <input type="text" name="name" ng-model="editProject.project.name">
</div>
   <label>Special instructions for this item</label>
   <textarea name="description" ng-model="editProject.project.description"></textarea>
<a href="#/" class="btn">Cancel</a>
<button ng-click="editProject.save()">Save</button>
</form>


<!--HTML for List of Items to Select-->

<tr ng-repeat="selection in selectionList.selections">
    <td>{{selection.type}}</td>
    <td>{{selection.cost}}</td>
    <td><button ng-click="(selection.type)">Select</button>
    </td>
</tr>

控制器:

//controller for form

myApp.controller('NewProjectCtrl', function($location, $timeout, Projects) {
var editProject = this;
editProject.save = function() {
    Projects.$add(editProject.project).then(function(data) {
        $location.path('/');
    });
};


//controller for list of items to select from

myApp.controller('SelectionListCtrl', function(Selections) {
var selectionList = this;
selectionList.selections = Selections;
});

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    我会这样想:创建一个服务并将其注册到 myApp 并在这里存储这两个控制器之间共享的数据。当您选择一个项目时,您在服务中注册它的值。

    然后你广播SelectionListCtrl中item的变化:$scope.$broadcast("new Item was selected")

    然后,在 NewProjectCtrl 中,您应该收听“选择了新项目”$scope.$on("new Item was selected"),在这里您可以从共享服务中获取值并在视图中显示或做任何您想做的事情

    【讨论】:

      【解决方案2】:

      就像 Feras 所说,您可以使用服务来设置和获取两种不同形式的值。

      我的设置和获取值的工厂

      app.factory('MainService', function() {
        var itemProd = [];
        return {
          setProd: function(item) {
            itemProd.push(item);
            console.log(itemProd);
          },
          getProd: function() {
            return itemProd;
          }
        }
      });
      

      如果你需要完整的代码,这里是我的小提琴“http://plnkr.co/edit/hvxI2ABmMBR6bNyKViFC?p=preview

      【讨论】:

      • 谢谢。不过,我无法让你的 plunker 工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多