Ruby on Rails - AngularJS добавляет новую запись

0

В моем приложении Ruby on Rails я пытаюсь добавить новую запись через AngularJS. Я использую этот метод:

Я создаю ресурс, называемый уведомлением:

rails g resource notifications title:string body:text

и я заполнил его:

Notification.create!(title: "Test1", body:" Some Text here")
Notification.create!(title: "Test2", body:" Some Text here")
Notification.create!(title: "Test3", body:" Some Text here")
Notification.create!(title: "Test4", body:" Some Text here")

я передаю все данные Json (находится в http://localhost: 3000/application/notification)

я установил теперь некоторые угловые js:

app.controller('notificationCtrl', ['$scope', '$http', function ($scope, $http) {

    // array for the notifications
    $scope.notifications = [];

    // method for get the notification
    var retriveNotifications = function(){
        // Console Log
        console.log(' Sto preparando le notifiche ');
        // trying to get to the notification page
        $http.get('/application/notifications').success(
            // getting the notifications
            function(items){
                $scope.notifications = items;
            }); 
    };

    //add a notification
    $scope.updateNotifications = function(title, body){
         var item = {title: title , body: body}

        $http.post('/application/notifications', item);
    }


    retriveNotifications();


}])

это мой html файл:

<form ng-submit="updateNotification()">
    <input ng-model="notificationName" placeholder="Title of the notification">
    <input ng-model="notificationText" placeholder="Body of notification">
    <input type="submit" value="Send"> 
</form>
<ul ng-repeat="notification in notifications">
    <li>
        <h4>{{notification.title}}</h4>
        <p>{{notification.body}}</p>
    </li>
</ul>

Я новичок Angular JS, и я знаю, что функция updateNotifications ошибочна. Как я могу вставить (в базе данных Notification) новую запись с Angular JS?

Спасибо за помощь

  • 1
    В форме вы вызываете updateNotification() , но в контроллере метод называется updateNotifications . Не уверен, что это единственная проблема, но первое, что появилось у меня.

1 ответ

1
Лучший ответ

Сначала в вашей функции уведомления об обновлениях есть тип

в вашем html файле это updateNotification();

в вашем js файле это updateNotifications также удаляет параметры заголовка и тела из функции, поскольку вы не объявляете их в своем html

для добавления новой записи используйте метод push для вашего массива

     app.controller('notificationCtrl', ['$scope', '$http', function ($scope, $http) {

// array for the notifications
    $scope.notifications = [];

   $scope.newItem ={};

// method for get the notification
    var retriveNotifications = function(){
    // Console Log
     console.log(' Sto preparando le notifiche ');
    // trying to get to the notification page
    $http.get('/application/notifications').success(
        // getting the notifications
        function(items){
            $scope.notifications = items;
        }); 
};
  $scope.updateNotifications = function(){
      var title = $scope.notificationName;
      var body = $scope.notificationText;
     var newItem = {title: title , body: body}

    $http.post('/application/notifications', newItem);
    //push your new item to notification array of records 
    $scope.notifications.push(newItem);
     $scope.newItem = {};
    }

    retriveNotifications();


 }])

Я настоятельно рекомендую использовать этот экран для начала использования рельсов с угловыми

Угловые и рельсы (railscasts.com

  • 0
    Спасибо, приятель =)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню