Having trouble with Angular + Rails combination: Angular can't seem to locate the controller

Issue: I am encountering an error in my Angular / Rails app. When trying to access a Rails controller function from the Angular controller, I receive the following error:

Uncaught TypeError: tasks.moveOrder is not a function
. Strangely, all other functions on the page are accessible.

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 specific function 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

All these functions possess routes and are invoked through my angular controller:

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 // places position as field in db (needs updating 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) // Calling the .rb file fails here!
        });
    };

    ...

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');
}]);

Could the failure of this function call be due to incorrect code implementation or some other underlying issue?

Answer №1

Make sure to refer to the documentation on $resource for more insight. While RESTful routes are available, additional actions must be explicitly defined and mapped to the corresponding controller actions. This can be achieved by setting up your module like this:

app.factory('Tasks', ['$resource', function($resource) {
return $resource('/tasks/:id', null,
  {
    'moveOrder': { method:'POST', url: 'route_to_your_action' },
    'otherAction': { url: 'route_to_your_action' }
  });
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can the swap operation be carried out using web3.js and a forked HardHat implementation?

Embarking on my journey into ethereum development, I am currently engrossed in crafting a basic script that facilitates swaps using web3.js. To begin with, my web3 is establishing a connection to the HardHat forked server. The first step involves setting ...

iOS devices are experiencing issues with touchstart and touchend events not functioning when utilizing jquery mobile and cordova

During a previous project, I encountered no problems with the following code snippet. It effectively utilized touchstart and touchend events to adjust the CSS of a button: <script> $('input[type="button"]').on('touchstart', func ...

Upon initial page load, React JS is unable to fetch the data but it functions correctly when triggered by a click

Here is the code I am working with: var CommonHeader = require('./header/CommonHeader.jsx'); var ListOptions = require('./header/ListOptions.jsx'); var SortableTable = require('../shared/SortableTable.jsx'); var ColumnDefinit ...

How to direct the main route to a sub route using AngularJS

The main template Home has two sub-templates called section1 and section2. Below is the routing code for reference: $urlRouterProvider.otherwise('/home/section1'); $stateProvider .state('home', { url: &apo ...

Troubleshooting: Issues with Adding a New Row in Datatables using JQuery

CSS : <div class="datatable-header"> <button type="button" name="add" id="add" class="float-right btn btn-info">Add</button> </div> <div class="table-responsive"> <table ...

The battle between Hover, Focus, and Blur modes intensifies

My goal is to implement 4 different effects on an element: When hovering over the element. When moving away from the element. When focusing on the element. When blurred. However, I'm encountering a conflict where when I focus on the element, the ...

Utilizing jQuery to Calculate Tab Scores

Last week, my teacher and I collaborated on a fun game called rEAndom game (). The game is created using javascript, jQuery, and HTML5. One interesting feature of the game is that when you press the TAB key, a div displaying the score appears. You can chec ...

Preventing Multiple Login Attempts in Angular.js Using Typescript

Is there a way to maintain the user login attempts limit even after page refresh? login() { /* Check if user has fewer than 5 failed login attempts */ if (this.failedAttempts < 4) { this.auth.login(this.credentials).subscribe(() => { this.rou ...

Retrieving location data using the Google Maps geocoder

Could someone help me with this issue in my code? function getLocationName(latitude, longitude) { if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) { return false; } var locationName; var geocoder = new google.maps. ...

The inclusion of a content editable feature within a carousel is leading to unexpected event propagation

I am dynamically creating an editable div using the code snippet below. <div class='reflection-field' contenteditable="true" data-number="${index}"></div> Expected Outcome: When I click on the generated div, I anticipate that the c ...

What are the best practices for implementing media queries in Next.js 13.4?

My media queries are not working in my next.js project. Here is what I have tried so far: I added my queries in "styles.module.css" and "global.css" and imported them in layout.js I included the viewport meta tag under a Head tag in layout.js This is how ...

What is the most efficient way to substitute text within an HTML document?

Is there a way to switch between languages on a website to replace text on multiple pages with a simple button click? What is the most efficient method for achieving this? This code snippet only changes text in the first div. Is there a way to implement a ...

Deleting an item in Vue.js with the removal feature

After deleting items from my list, they remain visible until I manually refresh the page. How can I fix this issue? List <tbody> <tr v-for="school in schools" v-bind:key="school.id"> <td>{{ school.id }}</td> &l ...

Issues with Angular displaying filter incorrectly

Whenever a user chooses a tag, I want to show only the posts that have that specific tag. For instance, if a user selects the '#C#' tag, only posts with this tag should be displayed. This is how my system is set up: I have an array of blogs that ...

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

Ways to retrieve information from the object received through an ajax request

When making an AJAX request: function fetchWebsiteData(wantedId) { alert(wantedId); $.ajax({ url: 'public/xml/xml_fetchwebsite.php', dataType: 'text', data: {"wantedid": wantedId}, typ ...

Javascript adds a comma after every postback event

This particular JavaScript code I am incorporating helps in expanding and collapsing nested grid views. <script type="text/javascript"> $("[src*=plus]").live("click", function () { $(this).closest("tr").after("<tr><td></td ...

What is the best method to eliminate a "0" entry from a javascript event array?

Hello, I've got an array structured as follows: let test = ["testOne:,O,U,0","testTwo:R,C,0","testTree:1.334","testFour:r,z"]; I'm looking to iterate through the array and remove any occurrences of the cha ...

Make an element in jQuery draggable but always within the viewport

My issue is that when I resize the window, the element stays in its position until I start dragging it. Once I drag it and then resize the window again, it doesn't stay within its container. To better illustrate my problem, you can view a demo on Fid ...

Show only the present y-coordinate in the ToolTip of a chart.js

I am currently working on developing a chart using Chart.js, and my goal is to only show the y-axis value in the tooltip. The current display shows: date name_of_line: measurement example: Jan 1, 2020, 8:00:00 AM 5th Percentile: 100 oz. However, I would ...