The ng-model does not update the value set in the controller

After testing out my code, I noticed that the following snippet in my view performs as expected. The player_id gets updated whenever a new selection is made:

<div class="form-group">
    <select class="form-control" ng-model="player_id" ng-change="hithere();">
        <option ng-repeat="player in players" value="{{ player.id }}">{{ player.name }}</option>
    </select>
</div>
test works: {{ player_id }}

However, the code snippet below doesn't behave as anticipated. Despite my selections in the view, the log consistently displays the default value of 0:

$scope.player_id = 0;
...
$scope.hithere = function($event){
    console.log('Test does not work, prints 0');
    console.log($scope.player_id);
};

I'm puzzled by this discrepancy. Any insights on what could be wrong?

Answer №1

It seems like a scoping dilemma. The $scope defined in the controller may be a higher level scope compared to the one in the HTML.

Try implementing the following:

$scope.data = {
  player_id: 0
}

Subsequently, utilize data.player_id across your code instead of just player_id.

Refer to Understanding Scopes for further insights.

Answer №2

One ideal situation for implementing the ControllerAs syntax is shown in this scenario.

To achieve this in your HTML, you can utilize the following code:

ng-controller="NameOfController as vm"

By doing so, your HTML will look like the example below, eliminating the need to enclose your model within an additional object.

<div class="form-group">
    <select class="form-control" ng-model="vm.player_id" ng-change="hithere();">
        <option ng-repeat="player in vm.players" value="{{ player.id }}">{{ player.name }}</option>
    </select>
</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

The content inside an HTML element and covertly deciphered quotations

SETTING THE SCENE: Hidden within the page lies a perfectly structured JSON object, wrapped in a div. Within this object are HTML values encoded with double-quotes, creating a unique challenge: "additionalInfo": "If you need more help, please visit &l ...

Variables are losing their way in the vast expanse of self-submitting

I have a form that needs to be submitted on the same page (index.php) and I want to capture the entered information as a JavaScript variable. <?php $loginid = $_POST[username] . $_POST[password]; ?> Here is some basic code: <script> var pass ...

jQuery input checkboxes validation conflict

There seems to be a strange issue with my checkboxes in the table where I have built an Invoice calculator. You can view it here. My goal is to have the inputs for Iva or Irpef not calculated in the Total Amount once they are checked. In the linked example ...

Guide to creating a multiline series chart in d3.js with json information by utilizing angular directives

I came across this link which shows a graph with csv data. However, I have json data and I'm attempting to create a graph using angular directives. Can someone assist me with this issue? Below is my angular directive in JavaScript: angular.module(&a ...

Using data across multiple instances in node.js EJS partials

I need some advice regarding my nodejs project. I have created a sidebar partial that requires user data to be displayed on it. This sidebar is utilized across multiple pages in the project. However, currently, I have to include the user data in every func ...

Adjust Navbar Header Color Based on Screen Size

I am completely new to front-end development. I am in the process of building my own responsive website using Bootstrap 3. One issue I am facing is that when I resize my browser window to simulate a phone screen, I want the navigation bar color to change ...

What could be causing the submission failure of the form post validation?

My Code: <form method="post" name="contact" id="frmContact" action="smail.php"> ... <label for="security" class="smallPercPadTop">Please enter the result:</label> <br /><h3 id="fNum" class="spnSecurity"></h3>& ...

Troubleshoot the issue of the service function not being triggered

Seeking help with my Angular project as I am facing an issue with resolve and $resource. Despite spending a whole day on it, I couldn't find a solution. When using resolve to fetch data with $resource and ui-router, the service method never gets calle ...

Incorporate an image into a div element with the power of jQuery

As the user scrolls down the page, a sticky menu or floater bar appears. With the help of jQuery, I am able to apply the floater-bar class to the #menu-wrapper. My objective is to also insert an image inside an anchor tag at the same time the floater-bar ...

Is there a technique to block small increments in a Time Input field?

Currently in the process of developing a tool to automate task scheduling within an Angular app. I am looking for a way to restrict the user's input when selecting the hour for task execution without having to install a complex input management packag ...

My JavaScript code is not triggering during the page load. Could this be related to .net

I've been attempting to trigger a JavaScript function upon the refresh of an update panel, but for some reason it's not working. Oddly enough, I'm using the same approach that has worked for other functions. In C#, this is what I have in th ...

Exploring the Intersection of Windows 8 Store Applications and jQuery: Leveraging MSApp.execUnsafeLocalFunction

Developing a Windows 8 JavaScript Store App (using Cordova) has led to some complications when using jQuery. It seems that in order to utilize certain functions, I have had to modify the jQuery library by adding: MSApp.execUnsafeLocalFunction While this ...

Ways to store the output of a <script src> tag into a variable

How can I retrieve the output of a file in JavaScript? I am looking to achieve: var list = <script src="src/users.json"></script> Is it feasible to accomplish this using JavaScript? ...

Why won't the state change when using Angular's ui-router $state.go method?

I have developed a factory that is responsible for detecting state changes and checking if a form has been modified. When the form is dirty, a modal window like a confirmation prompt should appear. However, I am encountering an issue where the $state.go() ...

What could be the reason for Angular to merge the element at index 0 of an array into a subarray instead of doing

After setting up the Array in my oninit function, I encountered an issue where one part of the array was functioning as intended while the other returned an error. this.tests = [{ status: 0, testresults: [{ name: 'test ...

The jQuery framework is causing AJAX/API data to be duplicated in the

I've been encountering a common issue for which I can't seem to find a straightforward solution. My current challenge involves using an API to fetch JSON data through an AJAX call. Upon receiving the data, it appears twice in both the console an ...

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

Calculating the total sum in Vuejs when an event is triggered

I am faced with a situation where the price of a product is added to an existing total when a user increases the quantity. However, the problem lies in the fact that even if the user decreases the quantity, the price continues to increase. Solution html ...

How does this code `/(s+(W)/g, '$1')` remove spaces?

let a = ' lots of spaces in this ! ' console.log(a.replace(/\s+(\W)/g, '$1')) logs out lots of spaces in this! The regex above efficiently accomplishes my goal, but I am curious about the reasoning behind it. I have ...

What is the specific function of $('id').on('click', this.method.bind(this)) in this scenario?

Check out the app I'm talking about here: I am delving into the bind method in JavaScript to grasp its essence. Upon experimenting with it in the console, my interpretation is that bind produces a duplicate of the function, wherein "this" is tethere ...