Unable to assign value to this.name within a $scope function in AngularJS

After developing an AngularJS application using Skinny AngularJS Controllers, everything seems to be functioning correctly. However, I have encountered a problem with the $scope.submit method. I am trying to assign a value to this.name, and then retrieve it using the this.getDetails method. Unfortunately, the value is not properly binding with the this.name variable.

If anyone has a solution to this issue, please let me know.

JSFiddle

script

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {

    this.getDetails = function () {
        return this.name;
    };

    $scope.submit = function () {
        this.name = "Messi";
    };
});

Answer №1

There is an issue with the code in $scope.submit, where the reference to this points to $scope instead of your controller. Here's a revised version that should function correctly:

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {
    var vm = this;
    vm.getDetails = function () {
        return vm.name;
    };

    $scope.submit = function () {
        vm.name = "Messi";
    };
});

In my opinion, it's best practice to stick with either using $scope or this, not mixing both. Remember to call one.submit() in your HTML :

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {
    this.getDetails = function () {
        return this.name;
    };

    this.submit = function () {
        this.name = "Messi";
    };
});

Edit: Please refer to this guide for the advantages of storing this in a variable like vm https://github.com/johnpapa/angularjs-styleguide#controllers

Answer №2

Here is a variation of the scenario:

let app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {
    let _self = this;

    _self.getName = function () {
        return _self.name;
    };

    $scope.save = function () {
        _self.name = "Ronaldo";
    };
});

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

The Jquery confirmation dialogue does not seem to be functioning properly within the Content Place Holder

I've encountered an issue with a JQUERY Confirm dialogue where it works perfectly fine until I place it on a page that is within a masterpage. The confirm alert pops up for a split second and disappears. window.onload = function() { $("#ehi").cli ...

Custom sorting in JavaScript

I have a specialized sorting method that is defined as follows sortArrayBy: function(a, b, sortKey) { if (a[sortKey] < b[sortKey]) return -1; if (a[sortKey] > b[sortKey]) return 1; return 0; }, I am looking to enhance it ...

How should a string be properly converted to JSON format?

I am encountering an issue with converting the following string to JSON format const banner = " { "banners": [ { "startDate": "02/26/2021", "endDate": "12/25/2021","content": "Important ...

Utilizing a combination of MVC, jQuery, and Ajax to ensure that JavaScript is fully loaded before proceeding

Utilizing ASP.NET MVC and jQuery, I am loading a PartialView via Ajax which has its own accompanying JavaScript file. Upon successful retrieval of the html content, it is inserted into the DOM. However, there can be a delay between the insertion and the ex ...

oidc-client-js failing to display all profile claims that are supported by oidc-client-js

When setting up UserManager on the oidc-client-ts TypeScript module using the config object below: var config = { authority: "https://localhost:3000", client_id: "js", redirect_uri: "https://localhost:3001/callback.ht ...

Dealing with a socket.io CORS problem

After deciding to implement a websocket on my website, I opted to utilize the socket.io library. However, I've encountered a CORS error: Access to XMLHttpRequest at 'http://localhost:2021/socket.io/?EIO=4&transport=polling&t=NlbFGS2&apos ...

I must automate the process of navigating to a different page within my website

My current dilemma involves using the header() function in PHP to automatically redirect a user to another page on my site after they dismiss an alert() box. However, the desired outcome is not being met. Here are my requirements: 1) Display a JavaScript ...

Creating a custom data type with a specific value in GraphQL

I am new to graphQL and have some questions regarding it. After going through the documentation, I decided to build something of my own. Currently, my setup is quite simple. At the beginning of my application, I have the following code: const express = ...

Exploring the combination of Meteor's Flow router or Iron router with the powerful Angular UI

I am currently working on integrating server-side rendering with distinct root HTML files into my Angular-Meteor project. However, since Angular does not inherently support server-side rendering and the iron router/flow router that enables this feature w ...

Who gets the callback when onreadystatechange is triggered in a single-threaded JavaScript environment?

Having recently delved into the world of JavaScript, I've come across the fact that it is single-threaded. My initial assumption was that when making an asynchronous request, a separate thread would be started to monitor the server's response. Ho ...

Exploring the Possibilities of Message Embeds in Discord using JavaScript

My goal is to teach my bot how to scan the description of embeds for a specific phrase. After reviewing the documentation at https://discord.js.org/#/docs/main/v11/class/MessageEmbed?scrollTo=description, it appears that I need to implement code similar to ...

PHP's counterpart to the Javascript XMLHttpRequest

Recently, I have come across a PHP function that is quite interesting: function saveSnapshot() { header("Content-Type: application/JSON: charset=UTF-8"); global $CFG; $resString = "{\"Success\": \"True\"}"; $snapshotNa ...

I successfully created a Chinese writing practice deck in Anki, which is functional on the desktop version but unfortunately not compatible with Ankidroid

While AnkiDesktop is functioning properly, there seems to be an issue with character encoding in Ankidroid. Despite trying numerous solutions, the problem persists. The character length displays correctly in Anki Desktop, but not in Ankidroid. For example ...

Rows in a table will not decrease when added anew

On a page that allows adding and deleting rows from a table of input fields, the following code functions properly for existing fields. However, when attempting to add new rows and delete them in a sequential manner that requires replacing the ID and name ...

Ways to divide a string into pairs of two using jQuery

I have a variable containing a string with exactly 44 characters: 02081516171821242936374750565865666871737476 I want to split it into an array in the following format: arr[0]=02 arr[1]=08 . . arr[21]=76 Can someone help me achieve this? Thank you. UP ...

How come the Jquery :odd selector picks out the even elements?

<html> <head> <script type="text/javascript" src="jquery-1.7.1.js" ></script> <script type="text/javascript"> $(function() { $("p:odd").html('modified'); }); </script> </head> & ...

Utilizing ng-options value in ng-change

Having a bit of trouble with my ng-options select tag. It seems like the ng-change function isn't working as expected, with the first parameter "v" coming up undefined. Anyone have any ideas on how to resolve this? <select ng-model="d.sub_customer ...

Is there a way to apply a consistent border to both the input radio button and its corresponding label once the radio button has been selected

CSS: <div class="form-check fs-3 mb-3"> <input id="first_question" name="first_question" type="radio" value="n"> <label for="first_question">no</label> </div> Is ...

Can a single ui-view in index.html be used to accommodate nested states with UI router?

As I am working on setting up a project and utilizing ui-router, one of the requirements is to have a URL that continues to append like #/home/contacts. To accomplish this, nested states need to be used. For example, home and home.contacts, where the home ...

Implementing a pre-defined value for ajax in ajax programming for beginners

I'm looking for guidance on setting up a hardcoded value for the OnSuccess parameter. The code I'm referencing is not my own, but I believe it may be related to Ajax. I'm a bit confused about it. Specifically, I need to focus on the OnSucce ...