The selected value in the ng-model is not defined

In my HTML, I have a select box with options generated from an ng-repeat.

<select ng-model="pageId" ng-change="setFacebookPage()">
    <option ng-repeat="page in pages" ng-value="page.id"> {{page.name}}</option>
</select>

Everything seems to be working correctly as the values and options are displayed properly. However, when trying to access the value of pageId in the function setFacebookPage(), it turns out to be undefined within the controller.

$scope.setFacebookPage = function(){
    console.log("setFacebookPage", $scope.pageId);
}

Interestingly, if I change the value of pageId, I can see its new value using {{pageId}}.

I attempted passing it as a parameter in the function like setFacebookPage(pageId), but that also resulted in an undefined value.

What could be causing this issue and how can I go about solving it?

Answer №1

Your code contains some minor errors that need to be addressed.

  • Ensure you are using the select element correctly
  • Avoid using commas between attributes

To correct these issues, consider updating your code as shown below:

 <select ng-model="pageId" ng-change="setFacebookPage()">
     <option ng-repeat="page in pages" ng-value="page.id"> {{page.name}}</option>
 </select>

You can test the revised code here

Answer №2

It is recommended to use

<select ng-model="pageId" ng-change="setFacebookPage()">
      <option ng-repeat="page in pages" ng-value="page.id"> {{page.name}}</option>
 </select>

instead of

<input type="select" ng-model="pageId", ng-change="setFacebookPage()">
    <option ng-repeat="page in pages" ng-value="page.id"> {{page.name}}</option>

DEMO

var app = angular.module('demo', []);

app.controller('myCtrl', function($scope) {
    $scope.pages = [{"id" : 1, "name" : "sachin"}, {"id" : 2, "name" : "sourav"}];
  $scope.setFacebookPage = function(){
    console.log( $scope.pageId);
}


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <body ng-app="demo" ng-controller="myCtrl">
    <select ng-model="pageId" ng-change="setFacebookPage()">
      <option ng-repeat="page in pages" ng-value="page.id"> {{page.name}}</option>
    </select>
  </body>

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

Aligning container divs at the center in various screen resolutions

I recently constructed a portfolio website using Bootstrap and Isotope JS. In my layout, I have a container div which works perfectly when viewed on a desktop browser - displaying 3 divs in one line. However, the issue arises when the resolution changes an ...

Consistently encountering incorrect values during onClick events

I am using a Table to display certain values const [selected, setSelected] = React.useState<readonly number[]>([]); const isSelected = (id: number) => selected.indexOf(id) !== -1; return ( <TableContainer> <Table sx={{ width ...

The output in Javascript featured the term undefined

var counter = 0; var message = 'Join us for our Christmas Family Service on Sunday, December 19th at 11:45 am. Explore the true essence of Christmas at Bethany Evangelical Church.'; /* The text */ var speed = 50; /* The speed/duration of ...

Developing a jQuery Plugin to Generate an Interactive Dropdown Menu

I have a task to dynamically create a select list in which users can add options after the select list has been created. Check out my code snippet below: <script type="text/html" id="select_field"> <div class='row& ...

Dealing with local JSON data asynchronously using ReactJS

Within my local workspace environment, there lies a valuable data.json file. Our application operates solely on the client side. I find myself torn between two potential methods of data consumption: import data from './data.json' // and start w ...

What method can be used to verify if Handlebar.js is integrated into the application?

I am struggling to verify the presence of Handlebar JS on the application's HTML page. No matter what I do, it keeps throwing an error saying "Uncaught Reference Error - Handlebars is not defined". Can anyone provide guidance on how to fulfill this ta ...

How can I create a menu of buttons in Vue that open individual windows with unique URLs when clicked?

Javascript Code: function InitializeVue() { var vueOptions = { el: '#activeEvents', data: { activeEvents: [] } }; vueInstance = new Vue(vueOptions); } HTML Code: <table id="activeEvents"> ...

An issue has occurred: Unable to access information of unknown origin (reading 'admin')

Hey there, I am encountering an issue when attempting to restructure my project as MVC. I am implementing use cases in my models with the goal of organizing my structure like this: When a route is accessed, it goes to the controller and then the controller ...

Navigating a JSON object using jQuery

My current project involves sending a Json response to an Ajax function within my webpage. The structure of the Json response is as follows: {"one": 21, "two": 10, "three": 19, "four": 100} With this setup in place, I am now in the process of developing ...

Capture all URLs containing [...slug] and generate static props only for valid addresses in Next.js

I am utilizing dynamic routes with the fallback:true option to ensure newly created pages are accepted. First, I check if the parameters are true, then I create related props and display the component with those props. In the console, I can observe that Ne ...

The Angular application sent an OPTIONS request instead of a POST request via HTTP

I'm encountering CORS errors while attempting to send HTTP requests from my angular.js application to my server. The code used to make the HTTP request is as follows: functions.test = function(foo, bar) { return $http({ method: 'POS ...

Canvas cannot be duplicated due to tainting, html2canvas

I have encountered an issue with my Snapshot button in HTML. Despite trying to add crossorigin="anonymous" to my script, I am still facing the problem of a Tainted Canvas when clicking the button. The button function is as follows: $('#snap').cli ...

Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". H ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

Error: The property 'open' is not defined in the mdMenu object

Encountered a bug while working with angular-material design... When using md-menu, if a sub menu item is opened (as shown in the image) and then hovering over a non-subMenu item (menu item), it throws an error "Cannot read property 'open' of nul ...

Can you explain the meaning behind this specific AngularJS declaration?

I am currently immersed in the book Angularjs, which highlights the process of Angular traversing the template to identify directives and bindings. This then leads to the registration of listeners, DOM manipulation, and acquiring initial data from the serv ...

What is the best way to determine the node version for executing the ng build command?

My current setup involves having two different versions of Node installed - 11.6 and 13.6. The default node version in the path variable is set to 13.6v. However, I have a project that specifically requires building with version 11.6v. Despite this, when u ...

What is the best way to incorporate a rectangle or arrow into my canvas design?

Looking for a way to enhance my html canvas wind direction code, here is how it currently looks: var x, y, r, ctx, radians; ctx = window.compass.getContext("2d"); radians = 0.0174533 * (10 - 90); x = ctx.canvas.width / 2; y = ctx.canvas.height / ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...