简体   繁体   中英

How to nest forms with angularjs?

I'm making an app that is not 100% 'single page' driven. I'm only using angular as a 'helper' as I ease into learning this new JS framework. Lots of my app is still controlled with plain old get and post, not angular resource or anything.

I have an outer form which is created by rails (it has an action="" etc).

Inside this form I have three "lists", kind of like 3 different kinds of todo lists but all in a single form that will be sent to rails when they submit it.

In one of the lists, the user will see a textbox that they can add new tasks. I'm trying to make it so a user can hit 'enter' in the text box and it adds it to the model, but withOUT submitting the parent form.

I've read that I can do this with ngForm with angular (to make it appear to nest forms) but I'm not sure how to do this or what is wrong. Here is my code:

main.js.coffee

app = angular.module("Messenger", [])

app.factory "NewTasks", ->
  NewTasks = []

@processNewCtrl = ["$scope", "NewTasks", ($scope, NewTasks) ->
  $scope.tasks = NewTasks

  $scope.addTask = ->
    task = $scope.newTask
    task.timestamp = new Date().getTime()
    $scope.tasks.push(task)
    $scope.newTask = {}
]

@processTomorrowCtrl = ["$scope", ($scope) ->
]

view.html.erb

<form action="/stuff">
    <!-- ... boring code-->
    <div ng-controller="processNewCtrl">
        <!-- ... ng-repeat unordered list here for task in tasks -->
        <div class="task">
          <angular ng-form ng-submit="addEntry()">
            <input checked="checked" disabled="disabled" type="checkbox">
            <input ng-model="newTask.description" type="text" autocomplete="off" placeholder="Additional Task description">
          </angular>
        </div> 
    </div>
    <!-- ... -->
</form>

Use ng-form along with ng-submit=mySaveCallback()

mySaveCallback() should handle sorting through data and then manually post to the backend (using $http or $resource or something).

Typically you don't use the traditional <form action="submit.html"> in AngularJS since you usually want to massage the data before sending it off, or update AngularJS in some way too. Using a traditional form request will also make you change the page which may also not be desirable.

Now if you're talking about keeping the traditional approach (changing pages and passing POST data) I honestly don't know how to do that off the top of my noggin in Javascript (as that's not an Angular-specific question).

But in my opinion, you're better off just fully converting to submitting all forms asynchronously using AngularJS and ng-submit . And it will be easier to work with in the future too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM