2015-08-06 4 views
0

В моем приложении Ruby on Rails я пытаюсь добавить новую запись через AngularJS. Я использую этот метод: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/notifications)

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

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> 

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

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

+1

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

ответ

1

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

в вашем HTML-файла является updateNotification();

в ваших JS файл, он updateNotifications также удалить заголовок и тело Params из функции, как вы не объявляя их в HTML

добавить новый метод записи простое использование нажимной в массив

 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(); 


}]) 

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

Angularjs and rails (railscasts.com

+0

Спасибо, бутон =) – giovaZ

Смежные вопросы