AngularJS Setting Default Values in HTML Pages

My goal is to set the default value for a dropdown in an Angular HTML Page. The page uses tabs, and I want the default value to load when a specific tab is clicked.

<div class="col-md-9" ng-cloak ng-controller="ServiceTypeController">
 <md-content>
   <md-tabs md-dynamic-height md-border-bottom md-selected="selectedIndex">
    <md-tab label="Details">
        <div ng-include="'././Views/Angular/Requests/details.html'"></div>
    </md-tab>

    <md-tab label="Create Request">
        <div ng-include="'././Views/Angular/Requests/createRequest.html'" md-on-select ="clearRequest(requestForm)"></div>
    </md-tab>
</md-tabs>
</md-content>
</div>

When the Create Request tab is clicked, it should trigger the clearRequest function. This function is defined as follows:

  $scope.serviceReasons = [
    { id: 1, value: 'ABC' },
    { id: 2, value: 'DEF' }
   ];

$scope.clearRequest = function (form) {
    $scope.request = {
        serviceReason : "ABC",
    };
    form.$setPristine();
    form.$setUntouched();
};

Below is the code for the Create Request Page:

<form name="requestForm"> 
 <div class="form-group col-md-6 md-padding">
   <div class="text-primary">
     <h3>Create Request</h3>
    </div>

      <div>
        <label style="font-size: medium">Service Reason</label>
        <select name="serviceReason" class="form-control" ng-model="request.serviceReason" required>
            <option ng-repeat="serviceReason in serviceReasons">{{ serviceReason.value }}</option>
        </select>
        <div style="color:maroon" ng-messages="requestForm.serviceReason.$error"
             ng-if="requestForm.serviceReason.$touched">
            <div ng-message="required">This field is required</div>
        </div>
    </div>
    <div class="md-padding col-md-6">
        <div class="row form-group">
            <button type="button" class='btn btn-danger' ng-click="clearRequest(requestForm)">Clear</button>
            <button type="button" class="btn btn-success" ng-disabled="!requestForm.$valid" ng-click="createRequest(requestForm)">Create</button>
        </div>
    </div>
 </div>
 </form>

The clearRequest() function works perfectly from the clear button in the Create Request page. It seems that md-on-select isn't behaving like ng-click - what am I missing here?

Answer №1

Typically, it is recommended to assign the selected option from a list of available options:

  $scope.serviceReasons = [
    { id: 1, value: 'ABC' },
    { id: 2, value: 'DEF' }
   ];

$scope.clearRequest = function (form) {
    $scope.request = $scope.serviceReasons[0];
};

If the selected object is different (meaning not equal), then you must specify a track by expression, usually using the id:

$scope.clearRequest = function (form) {
    $scope.request = { id: 1, value: 'ABC' };
};
<select name="serviceReason" class="form-control" ng-model="request.serviceReason"
 required ng-options="s.value for s in serviceReasons track by id">
</select>

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

What is the process for changing the state of an array in graphql?

Currently, I am facing a challenge with adding an array to a GraphQl schema. Here is what it looks like: type Play { winRatio: [Float] } The intention behind the winRatio attribute is to store the history of all win ratios. For instance, after playing 3 ...

Press on a circle to adjust its size to fit the section or division

Is it possible to make a circle expand and fill the section/div when clicked? I want the circle to fill the screen upon clicking, and then have some text appear in its place. Before posting this, I searched on the web and came across this jsfiddle link. ...

Create a function in JavaScript that can generate a random number a specified number of times based on user input

I have been struggling to develop a JavaScript program that can generate a random number multiple times based on user input. Despite numerous attempts, I haven't been able to get it to work. Below is the code snippet I've been working with: f ...

Utilizing hidden types for radio button validation in AngularJS: A step-by-step guide

<input type="hidden" value="{{r.radioname}}" name="{{field.Name}}" ng-model="inputfield[field.Name][r.radioname]" required> <input type="radio" id="radio_{{$index}}" value="{{r.radioname}}" name="{{field.Name}}" ...

"The combination of Node.js, Express, and Angular is causing a continuous loop in the controller when a route is

Currently, I am utilizing node js alongside Express. Angular js files are being loaded through index.html. The code for app.js is as follows: app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...

Can the V8 JavaScript engine made by Google be used on iOS devices?

Is V8 compatible with iOS? If not, what embeddable JavaScript engine would you suggest? UPDATE: We will only be using it for internal scripting purposes, rather than in combination with HTML rendering. ...

The pre-set value in the search bar of the Google specialized search

Is it possible to pre-fill the search field with text when the Google Custom Search page is loaded using the standard copy and paste code (free with ads)? If yes, how can this be achieved? Below is the code snippet: <div id="cse" style="width: 100%;" ...

Display the Bootstrap tooltip when an Angular input field is in focus and has encountered an error

This specific example was extracted from the angularjs documentation <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Req ...

What is the best way to incorporate dynamic active tab functionality?

I want the tabs to become active every time I click on them. How can I achieve this? <ul class="nav nav-pills pull-left" role="pilllist"> <li class="active" data-placement="right" title="Voucher Details"><a data-toggle="pill" role="pil ...

The issue of dynamic select not sending the POST data

Having an issue with a form where the selected country and city are not being posted correctly. Despite different names in the form and php mailer script, both selections are coming through as the country. Here's the form: <select style="width: 6 ...

Issue: Alert: Middleware for RTK-Query API designated as reducerPath "api" is missing from store configuration even though it has been included

Currently in the process of migrating my application to NextJS, and I'm dealing with the following store configuration. It's a bit messy at the moment, but I plan on cleaning it up and reducing duplicated code once I have everything functioning p ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

Are Twitter Bootstrap buttons compatible with iPad devices?

Have you ever tried using the attractive buttons provided by Twitter? They can be a great alternative to standard radio/checkbox options. If you have used them in your production, how effective were they? I am particularly curious about their compatibilit ...

Unable to retrieve API data on local server port 5000. Utilizing a database sourced from a CSV file. Unexpected undefined promise response

I have been struggling for the past few days with a persistent issue. Seeking assistance. Currently working on a project involving a CSV database and creating my own API. It is a small React App Fullstack MERN setup. The specific challenge I am facing is ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...

Interacting between my React Native client and server.js

Currently, I am developing a project that utilizes react native, express, and MongoDB. My challenge lies in establishing communication between the react-native-js file and the node-js file. Specifically, when the submit button is clicked, I aim to pass a ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

"Communication breakdown in Vue.js: $emit event not being picked up by corresponding $

Vue.component('rating-edit', { template:` <form> <input v-model="rating.title" type="text"> <textarea v-model="rating.remark">{{rating.remark}}</textarea> <button type="button" @click=" ...

Error occurred due to an invalid element type with the imported React component

Using a component imported from an npm package in two different apps has resulted in unexpected behavior. In one app, the component functions perfectly as expected. However, in the other app, an error is raised: Element type is invalid: expected a string ...