Trouble with AngularJS: Default values not being set by ng-model

In this code snippet, I have set up ng-model to pass filter into my function and retrieve all user selections. Initially, I believed it could also be used to prefill or default the data. However, I am facing issues with this approach. Here is an excerpt from my controller:

.controller('ListCtrl', [
    '$scope', '$filter', '$location', 'context', 'breeze', 'Service',
    function ($scope, $filter, $location, context, breeze, Service) {
        $scope.pageLoaded = true;
        $scope.lists = [];
        $scope.DDL1 = '';
        $scope.filter = {
            fromDate: '2015-05-01',
            toDate: '',
            sales: false            
        };

Below is a snippet of the corresponding HTML:

<md-content ng-controller="ListCtrl" layout="column" flex class="md-padding">
    <md-tabs class="md-primary clearfix" md-selected="0" flex>              
        <md-tab label="Lists">
            <table><tr>
                <td width="10%">From Date: </td>
                <td width="40%"><input type="date" ng-model="filter.fromDate" value="{{filter.fromDate}}"/></td>
                <td width="10%">SParts: </td>
                <td width="40%">                                    
                    <input type="radio" name="sales" ng-model="filter.sales" value="true"> yes
                    <input type="radio" name="sales" ng-model="filter.sales" value="false" checked> no
                </td>...

Answer №1

Using String Data Type

If you are using the input type="radio", ensure that the data type of filter.sales is set to string in order for it to function correctly.

$scope.filter = {
    fromDate: '2015-05-01',
    toDate: '',
    sales: 'false'          
};

Clarification from AngularJS Documentation on input type="radio" ng-model here,

The value assigned to the ngModel expression must be a string value when selected. Note that only string values are supported. This means that the scope model should also be a string. Use ngValue if you require complex models (such as numbers or objects).

Answer №2

One way to prefill a radio button in AngularJS is by using the ng-checked directive based on another value.

For instance:

<td width="40%">                                    
  <input type="radio" name="sales" ng-model=vm.filter.sales > yes
  <input type="radio" name="sales" ng-model=vm.filter.sales ng-checked="true"> no
</td>

In the example above, I have manually set the ng-checked value to true, but you can also dynamically set it based on a controller variable. For more information, refer to the documentation at https://docs.angularjs.org/api/ng/directive/ngChecked

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

Tips for incorporating a callBack function when the screen changes in react-native:

Is there a way to implement a callback function that executes whenever the screen changes, such as moving from the home screen to the about screen? Situation I would like to create a global stack that triggers a callback function whenever any navigation o ...

How can I convert a list of checkboxes, generated by ng-repeat, into multiple columns?

Here is the HTML code snippet: <div class="checkbox"> <label> <input type="checkbox" ng-model="selectedAll.value" ng-click="checkAll()" />Check All </label> </div> <div class="checkbox" ng-repeat="carType i ...

"Error encountered: 'require' is not defined in the bundled JS file for

Recently, I decided to try my hand at Django and ReactJS. While attempting to compile a simple JSX code to JS, I followed this tutorial: . However, I encountered an error that prevented it from working. I then resorted to using npm run dev to compile the c ...

Unable to locate the <router-view> component within VueRouter

I recently completed a project using Vue.js 3.2.13 and Vue-Router 4.0.14. Despite my efforts to ensure everything was set up correctly, I encountered an error in the browser that said "[Vue warn]: Failed to resolve component: router-view". The specific lin ...

Building an organized framework for a Node project

Two of my applications are utilizing similar API functions, with one developed in Angular and the other in React + Flux. Both applications are required to interact with the same database. While my Angular application is responsible for adding new data to ...

Having trouble with importing SendInBlue into my NodeJS application?

Currently in the process of updating my Node app to utilize ES6 import modules over requiring files. Encountering difficulties while trying to integrate this change with SendInBlue for email functionality, resulting in the following error message: TypeEr ...

Discover exclusive outcomes within the Dropdown selection

I'm populating a select dropdown dynamically from a JSON array of objects and would like to filter by tag. The issue I'm facing is that I am getting duplicate tags because multiple results can have the same tag. How can I ensure that only unique ...

Spacing issues while utilizing the <textarea> element

<tr> <td> <b>Escalation: </td></b> <td> <TextArea name='escalation' onKeyDown=\"limitText(this.form.escalation,this.form.countdown,100);\" onKeyUp=\"limitText ...

Guide to importing external CSS styles into Angular 2 using the require method

I'm facing an issue with loading an external css file in different environment files. My setup includes two environments: development and production. Loading the css file locally works fine in development mode, but not in production mode. environment ...

Obtaining IP Address with Jquery or Phonegap: A Guide for Cross Platform Development

Is there a way to retrieve the IP address using Jquery or Phonegap? I am currently working on an application that is compatible with Android, iPhone, and Windows platforms. I'm in need of a solution to locate the IP address of a request. ...

What is the best approach for sending a binary image post request to an API using nodejs?

I am receiving the image binary in this manner: axios.get("image-url.jpg") Now, I want to utilize the response to create a new POST request to another server const form = new FormData(); const url = "post-url-here.com"; form.appe ...

"Stored on the server: A preview of a musical masterpiece

I am working on a website concept where users can preview a 30-second snippet of a song before making a purchase decision. My plan is to store all the mp3 files below the root folder to prevent direct access. My main concern is whether I can enable the 30 ...

Unable to instantiate a class object in TypeScript by using the new operator

Object instantiation is occurring without any issues: let paginationDetails: Common.Models.PaginationModel = { PageNumber: this.pageNumber, PageSize: this.pageSize, SearchText: this.denominationFilter, Ascending: true }; However, when att ...

Spring Security 3 does not support the use of static resources

I am facing difficulty in configuring static resources (such as js, css, images) in spring security 3. Here is my configuration file: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/s ...

Incorporating Entrance Animations for Individual Elements within ngView Using AngularJS

Can each content within ngView be animated individually upon entering, rather than the entire View (div) itself? ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

How can we add hover effects to Ionic / Angular components when touching or clicking?

For my app, I need to replicate the hover effect from CSS on mobile devices. Users can click and drag elements, and when they drag over certain elements, I want those elements to change z-index and other styles. Is there a way in Angular / Ionic or even ju ...

Bar graph width in Chart.js is displayed horizontally

Check out the bar chart image here: https://i.sstatic.net/RLeZp.png This particular graph was created using the code snippet provided below: var myChart = new Chart(ctx, { type: 'horizontalBar', data: { labels: labels, ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

Display only specific PHP-encoded JSON data in a formatted table

After receiving a variable from PHP, I convert it to JSON as shown below: var myData = <?php echo json_encode($json_array) ?>; When I log the output, it looks something like this: 0: Carat: "0.70" Clarity: "VVS2" Color: "D" Cut: "Very Good" Polish ...