問題:我寫了一個角/ Rails應用程序,當我試圖從角控制器訪問Rails控制器的功能,我得到一個錯誤:Uncaught TypeError: tasks.moveOrder is not a function
,但所有其他功能上該頁面可角+ Rails的:角找不到控制器功能
tasks_controller.rb
def index
respond_with Task.all
end
def create
respond_with Task.create(task_params)
end
def destroy
task = Task.find(params[:id])
task.destroy
respond_with task
end
def show
respond_with Task.find(params[:id])
end
def moveOrder # This is the function that cannot be found
task = Task.find(task_id)
task.position = pos
respond_with task
end
def up_completion
task = Task.find(params[:id])
task.increment!(:completion)
respond_with task
end
def down_completion
task = Task.find(params[:id])
task.decrement!(:completion)
respond_with task
end
private
def task_params
params.require(:task).permit(:title, :completion, :importance, :steps, :clicked, :position)
end
這些函數有路線和各功能是通過我的角度控制器稱爲:
MainCtrl.js
.controller('MainCtrl', [
'$scope',
'tasks',
function($scope, tasks){
$scope.tasks = tasks.tasks;
$scope.items = ['one', 'two', 'three'];
$scope.addTask = function() {
var taskPosition = tasks.tasks.length + 1;
if(!$scope.title || $scope.title === '') { return; }
tasks.create({ // This call to the .rb file works!
title: $scope.title,
importance: $scope.importance,
completion: 0,
steps: $scope.steps,
clicked: false,
position: taskPosition // puts position as field in db (needs to be updated when dragged)
});
$scope.title = '';
$scope.importance = '';
$scope.steps = '';
};
$scope.moveTask = function(start_pos, end_pos) {
$.get("http://localhost:3000/tasks.json")
.done(function(data) {
var task_id = data[start_pos].id;
tasks.moveOrder(task_id, end_pos) // This call to the .rb file fails!
});
};
...
app.js
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'MainCtrl',
resolve: {
taskPromise: ['tasks', function(tasks){
return tasks.getAll();
}]
}
})
.state('tasks', {
url: '/tasks/{id}',
templateUrl: 'tasks/_tasks.html',
controller: 'TasksCtrl'
});
$urlRouterProvider.otherwise('home');
}]);
是函數調用失敗,因爲我寫的東西不正確或者是有一些其他的問題,乾脆?
你不能從客戶端代碼調用服務器端函數。 (允許這將是一個嚴重的安全漏洞。)改爲使用AJAX請求。 – Ajedi32
那我爲什麼能夠調用其他函數呢?在'tasks_controller.rb'文件(即'tasks.create','tasks.up_completion','tasks.down_completion'(未顯示)等? –
Touché。我實際上不熟悉Angular,但我的猜測是否與'create','show','update'和'destroy'在默認情況下映射到Rails中的標準REST路由有關係,如果這確實是原因,那麼'up_completion'和'down_completion' shouldn不管用,只是'create','show','update'和'destroy'。無論如何,你都不是直接調用這些方法。AJAX幾乎肯定涉及到了(或者也許是websocket。我說,我實際上並不熟悉Angular),它只是由Angular自動處理,只是一個觀察 – Ajedi32