How do I save an Angular form to my ruby on rails backend?

后端 未结 3 2062
清酒与你
清酒与你 2021-01-05 18:46

I\'m new to Angular. I\'ve tried everything I know how and Google searches have surprisingly few tutorials on this particular question. Here\'s the last code I tried:

<
3条回答
  •  北海茫月
    2021-01-05 18:59

    Until your input fields are blank, no value is stored in model and you POST empty article object. You can fix it by creating client side validation or set default empty string value on needed fields before save.

    First of all you should create new Article object in scope variable then pass newPost by params or access directly $scope.newPost in addArticle fn:

    app.controller('ArticlesCtrl', function($scope, Article) {
      $scope.articles   = Article.query();
      $scope.newPost    = new Article();
    
      $scope.addArticle = function(newPost) {
        if (newPost.title == null) {
          newPost.title = '';
        }
        // or if you have underscore or lodash:
        // lodash.defaults(newPost, { title: '' });
        Article.save(newPost);
      };
    });
    

    If you want use CRUD operations you should setup resources like below:

    $resource('/articles/:id.json', { id: '@id' }, { 
      update: {
        method: 'PUT'
      }
    });
    

提交回复
热议问题