Utilizing Restangular to assign multiple parameters to a variable within the scope variable

Currently learning AngularJS and utilizing Restangular to communicate with a Rails server API. Struggling with grasping the concept of assigning form parameters to a variable in order to use it within my function for posting to the Rails API.

Below is an excerpt of my controller:

.controller('NewCtrl', ["$scope", "Restangular", function($scope, Restangular) {

  var passages = Restangular.all('passages');
  var allPassages = passages.getList();

  var newPassage = {
    book: $scope.passages.book
  }; 

  $scope.add = function() {
    passages.post(newPassage);
  };

This is how my form looks like:

<h1>Add New Passage</h1>
<form name="myForm" ng-submit="add()" ng-controller="NewCtrl" class="my-form">
  Book: <input name="passages.book" required><span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  <input type="submit" id="submit" value="Submit" />
</form>

Encountering the following error in the javascript console:

TypeError: Cannot read property 'book' of undefined
at new <anonymous> (http://localhost:9000/scripts/controllers/main.js:38:27)
at invoke (http://localhost:9000/bower_components/angular/angular.js:3000:28)
at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:3012:23)
at http://localhost:9000/bower_components/angular/angular.js:4981:24
at update (http://localhost:9000/bower_components/angular/angular.js:14509:26)
at Object.Scope.$broadcast (http://localhost:9000/bower_components/angular/angular.js:8468:28)
at http://localhost:9000/bower_components/angular/angular.js:7614:26
at wrappedCallback (http://localhost:9000/bower_components/angular/angular.js:6995:59)
at wrappedCallback (http://localhost:9000/bower_components/angular/angular.js:6995:59)
at http://localhost:9000/bower_components/angular/angular.js:7032:26 

Seems like I'm missing a crucial step in effectively assigning form values using $scope to a variable. When using a static value like book: "Ephesians," everything functions smoothly. Appreciate any guidance on resolving this issue.

Answer №1

Are you having issues with your controller? Let me help you fix it:

.controller('NewCtrl', ["$scope", "Restangular", function($scope, Restangular) {

    var passages = Restangular.all('passages');
    var allPassages = passages.getList();

    // Setting up $scope.passage:
    $scope.passages = {
        book: null
    };

    $scope.add = function() {
        passages.post({
            book: $scope.passages.book
        });
    };
}])

Here is the markup for your controller:

<h1>Add New Passage</h1>
<form name="myForm" ng-submit="add()" ng-controller="NewCtrl" class="my-form">
  Book: <input ng-model="passages.book" name="passages.book" required><span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  <input type="submit" id="submit" value="Submit" />
</form>

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

Troublesome CSS conflicts arise when using minified assets with AngularJS and Webpack

After transitioning my Angular project to the Webpack build system, I encountered issues with Angular Dependency Injection in the JS source code. Surprisingly, now I am facing JS errors that are targeting CSS files, leaving me completely bewildered about w ...

Display detailed images upon hovering

Top of the morning to everyone. I'm in search of a way to display higher resolution images when hovering over lower resolution ones. I want to create a rule or function that can handle this dynamically without manually adding hover effects and changi ...

The driver instance that has forked will never cease

Issues arise when attempting to run multiple browser windows in Protractor. The code snippet being tested is as follows: I create a new browser instance to perform certain tests. When input is entered into the original browser, it should not affect the ne ...

The method of inserting a JSON dates object to deactivate specific days

I am currently utilizing a date picker component that can be found at the following link: While attempting to use the disabledDays section below, I have encountered an issue where I am unable to apply all three options. The blockedDatesData option works o ...

Issue encountered: Unable to locate module: Error - Unable to resolve '@cycle/run' with webpack version 2.2.1

I am attempting to run a hello world application using cycle.js with webpack 2.2.1. The following error is being displayed: ERROR in ./app/index.js Module not found: Error: Can't resolve '@cycle/run' in '/Users/Ben/proj/sb_vol_cal ...

Unexpected issue encountered when working with JSON in Node.js

I've searched through countless solutions on stackoverflow, but none of them seem to work for me. It's really frustrating not understanding what's going wrong. Below is the code I'm having trouble with: var data = ""; req.on('dat ...

Trigger an alert after a separate function is completed with jQuery

On my page, I have a function that changes the color of an element. I want to trigger an alert once this action is complete using changecolor(). However, I am unable to modify the changecolor() function due to certain restrictions. Is there a way to dete ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

Tips for improving the readability of my code

This code snippet pertains to handling a POST request in Express.js with MongoDB integration. router.post('/', function(req, res){ var data = req.body; Tag.find({name: data.name}).limit(1).exec( function(err, result){ if(err) { // ...

Executing Node.js Function from an External File Dynamically

Is it possible to run a Node function from an external file that may be subject to change? main.js function read_external(){ var external = require('./external.js'); var result = external.result(); console.log(result); } setInterva ...

Why won't the click event work in Vue when using v-if or v-show?

Attempting to trigger a click event from a div, but if v-if false is present during component rendering, the click event does not work. Here's the code snippet: export default { name: "ProSelect", data() { return { isActive: false ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

My attempt to execute the JavaScript code was unsuccessful

Recently, I have been experimenting with the three.js library, a powerful javascript 3D library... Here is the code snippet I have been working on: var segments = 16, rings = 16; //var radius = 50; <-- original // Creating a new mesh with sphere geo ...

Alert received following installation of angular-ui-router

Upon installing angular-ui-router via npm install, the following message appeared: WARNING! The npm package "angular-ui-router" has been rebranded as "@uirouter/angularjs". Please update your package.json file. See https://ui-router.github.io/blog/uiroute ...

"Encountering issues with logging in through AngularJS and the $http request functionality

My goal is to login using $http and GET of REST web services. This is my approach: Retrieve data based on username and password using $http.get Store the result in $scope.getResult=res; Assign variables to the retrieved data: var result=$scope.getResult ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

Activate Vuetify to toggle a data object in an array list when the mouse hovers over

I'm currently working on a project where I need to toggle a Vuetify badge element for each item in an array when the containing div is hovered over. While I've been able to achieve a similar effect using CSS in a v-for loop with an array list, I ...

Error: No package.json file found after publishing npm package with ENOLOCAL

Ecosystem using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335d435e73051d021d03">[email protected]</a> using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a8a9a2a386b0fee8f7f7e ...

Issue with displaying the glyphicon-chevron on the carousel control

Currently, I'm in the process of incorporating a straightforward modal into my gallery design. I have a slide carousel positioned at the top of the page, while at the bottom, there are thumbnails of the gallery. While the slide carousel control butto ...

Issue with external JavaScript file being unresponsive on mobile browser

Hello everyone, hope you're having a great afternoon or evening I've encountered an issue with mobile browsers like Chrome Mobile and Kiwi where the external js file is not visible in the html file. The script.js file looks like this: alert(&ap ...