在我的Ruby on Rails应用程序中,我试图通过AngularJS添加新记录。我正在使用这种方法:
我创建了一个名为notification的资源:
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)
的所有数据我现在设置了一些角度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是错误的。我如何使用Angular JS插入(在Notification数据库中)一条新记录?
感谢您的帮助
答案 0 :(得分:1)
首先,您的更新通知功能中有一个类型
在你的html文件中是updateNotification();
在你的js文件中,updateNotifications也会删除函数中的title和body params,因为你没有在你的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();
}])
我强烈建议您使用此屏幕投射开始使用带有angularjs的轨道