ng-view scope interacting with parent scope connection

Excuse the late-night desperation, but I have a question about my AngularJS application that uses ngRoute. Currently, everything is being handled in one controller. The issue arises with a form in a view where I need to take the input field data and store it in a variable to send via post.

Please ignore the excessive console logs as I'm troubleshooting.

APP.JS

    $scope.addDevice = function(){
        $scope.device = {};

        var data = {
            'Name' : $scope.device.ChildName,
            'Serial' : $scope.device.Serial
        };

        console.log($scope.device.Serial);
        console.log($scope.device.ChildName);
        console.log(data);

        $http.post('http://141.135.5.117:3500/device/register', data, { headers: headers })
        .then(function(response){
            console.log(response);
            console.log(headers);
        });
    }

Settings.html ( Please note: this is a view within ng-view)

<form role="form" class='userForm'>
            <label for="addDevice">Add Device</label>
            <input type="text" class="form-control" id="deviceserial" placeholder="Enter serial number" ng-model="$scope.device.Serial">
            <input type="text" class="form-control" id="Devicechildname" placeholder="Enter baby name" ng-model="$scope.device.ChildName">
            <button type="submit" class="btn btn-success btn-block" ng-click="addDevice()">Add Device</button>
            <p>{{$scope.device.Serial}}</p>

</form>

This is the output from the console:

Console output

All functions are currently consolidated in one controller.

Answer №1

To start, remove $scope from ng-model="$scope.device.Serial" and declare $scope.device = {}; outside the $scope.addDevice function:

$scope.device = {};

$scope.addDevice = function(){ -- your code here -- }

Here is a functional code example:

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope','$http', function($scope,$http) {
     $scope.val = '1';
     $scope.device = {};
     
     $scope.addDevice = function(){        

        var data = {
            'Name' : $scope.device.ChildName,
            'Serial' : $scope.device.Serial
        };

        console.log($scope.device.Serial);
        console.log($scope.device.ChildName);
        console.log(data);
        $http.post('http://141.135.5.117:3500/device/register', data)
        .then(function(response){
            console.log(response);
            console.log(headers);
        });
    }
     
     
     
   }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="inputExample">
<div ng-controller="ExampleController">

<form role="form" class='userForm'>
            <label for="addDevice">Add Device</label>
            <input type="text" class="form-control" id="deviceserial" placeholder="Enter serial number" ng-model="device.Serial">
            <input type="text" class="form-control" id="Devicechildname" placeholder="Enter baby name" ng-model="device.ChildName">
            <button type="submit" class="btn btn-success btn-block" ng-click="addDevice()">Add Device</button>
            <p>{{device.Serial}}</p>
</form>

</div>
</div>

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

Dealing with a situation where different functions need to be called based on a condition while using unique button names. This is

<button type="button" class="btn btn-primary ms-4" (click)="update()">Save</button> <button type="button" class="btn btn-primary ms-4" (click)="create()">Add</button> B ...

The Mystery of jQuery Isotope Plugin: Why Can't I Add "display:none" Inline?

I'm currently in the process of integrating Isotope into my latest Wordpress theme. However, I've encountered an issue where it's not appearing on the page due to some external factor adding an inline style (display:none) to the main isotope ...

Utilizing MutationObserver in JavaScript for Streamlined Code Execution

One of my functions utilizes a MutationObserver to track attribute changes in a specified element and logs them to the console. Below is an example where I pass 'card' elements in a foreach loop: track_attr_changes(element); The parameter ' ...

Is there a way to prevent this React function from continually re-rendering?

I recently created a small project on Codesandbox using React. The project involves a spaceship that should move around the screen based on arrow key inputs. I have implemented a function that detects key presses, specifically arrow keys, and updates the ...

Conditionally render a div in React with Next.js depending on the value of a prop

Struggling with an issue in my app and seeking some guidance. The problem arises when dealing with data from contentful that has been passed as props to a component. Specifically, I only want to render a particular piece of data if it actually contains a v ...

Preserve the specific date and time in the designated timezone

Utilizing the react-datePicker library requires using new Date() as input. I need to save the user's selected date, time, and timezone in such a way that regardless of their location, they will see Feb 10 2024 02:00 BST in the Date Object. Currently, ...

What is the proper way to safely escape a JSON string for an object that contains user-generated content?

How can I correctly use the variable s for the value-field of an option-element while escaping user input used for key and value? var key='highway'; var value='track'; var s = JSON.stringfy({ [key]:value }, undefined,''); s ...

Utilizing Next.js and Redux for Enhanced Authentication Experience

I have encountered an issue while trying to authenticate the user upon loading and needing to run the authentication process in the pages/_app.js file. The error I am facing is useReduxContext.js:24 Uncaught Error: could not find react-redux context value; ...

Is there a way to transfer gulp.watch() to a pipe?

Currently, I have a basic task set up for linting changed JavaScript files: gulp.task('default', function() { // monitor JS file changes gulp.watch(base + 'javascripts/**/*.js', function() { gulp.run(&ap ...

Ways to dynamically assign a class to a single element within a group of identical elements

I have three identical items in the DOM. Specifically, I am referring to a moving line <span class="caret"></span> <ul> <li class="nav-item-1"> <a href="#">ITEM 1</a> <span class="caret"></span> ...

What is the process of embedding a string with pug code into a pug file?

How can I interpolate a string with pug formatted code in a pug file? Here is what I have tried: - var text = "i.home.icon" div= text div !{text} div #{text} div ${${text}} div {{text}} div {text} div \#{text} div \{text} div ${text} div # ...

HTML5 allows users to choose data from a list using a ComboBox and submit the 3-digit code

I'm looking to enhance my form by including an input box where users can select airports, similar to the functionality on this website (). When typing in the Destination Input, I want users to see a list of possible values with detailed suggestions su ...

Click and release file upload

I am working on creating a drag and drop upload feature where the user can drop files onto a div, and then click an upload button to send them to the server. I'm facing an issue with JavaScript not recognizing the variable fd. How can I pass that vari ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

Looping through JQuery change events

I have a challenge with handling checkboxes. Whenever a user checks one, I need to validate if they are permitted to do so. If not, I must notify them and uncheck the box. However, this process becomes recursive as it triggers the change event again! How c ...

Efficient PHP caching solution for optimizing JavaScript and CSS performance

I'm facing a unique challenge that I can't seem to solve through typical Google searches. I'm in the process of consolidating all my javascript and css into separate php files using require_once() to pull in the content. The structure of my ...

Encounter a Config validation error while trying to utilize Nest.js ConfigService within e2e tests

I'm encountering an error despite having the NODE_ENV=development variable in my .env file. The error message reads: ● Test suite failed to run Config validation error: "NODE_ENV" must be one of [development, production] 11 | imports ...

React- Error: Unhandled Type Mismatch in function call for _this4.getNotes

As I delve into learning React, I've created a basic application to manage notes with titles and descriptions. This application interacts with a REST API built using Go, enabling me to perform operations like retrieving, editing, creating, and deleti ...

angular material md-input with navigation

We have successfully implemented md autocomplete functionality. However, our specific requirement is to redirect to the corresponding page upon selecting a value from md-autocomplete. <md-autocomplete ng-disabled="isDisabled" md-no-cach ...

Divide the string into several segments according to its position value

Here is a piece of text that I would like to divide into multiple sections, determined by the offset and length. If you have any questions or comments and would like to get in touch with ABC, please go to our customer support page. Below is a function ...