Establishing the default value of an input field in Angular by referencing another field

Within an Angular (1.5) setting, I am confronted with a form containing two input sections:

  • ID
  • URL

The requirements are as follows:

  • If the ID section remains vacant, the URL field should likewise be left empty.
  • If the URL area is entered manually, it must not alter automatically afterward.
  • If none of the above apply, then the URL slot should autonomously show ""+ID+".txt"

What steps can be taken to bring about this desired outcome?

Answer №1

  <input type="text" name="website"
         ng-model="urlInput"
         ng-model-options="{ getterSetter: true }" />

...

    function setDefaultUrl() {
       if $scope.ID {
          return 'http://myurl/'+$scope.ID+'.html';
       } 

       return ''
    }

    var _defaultUrl = setDefaultUrl();

    $scope.urlInput = {
       url: function(newUrl) {

            return arguments.length ? (_defaultUrl= newUrl) : setDefaultUrl();
       }
    }

};

Answer №2

Implement a $watch function on the ID Field. This function will trigger whenever there is a change in the ID field.

$scope.$watch('$scope.ID', function() {
    $scope.url = 'http://myurl/' + $scope.ID + '.txt';
}, true);

Answer №3

Check out this fiddle I created to fulfill your needs:fiddle

Below is the code snippet:

//HTML

<div ng-app="myApp" ng-controller="MyController">
    ID <input type="text" ng-model="data.id" ng-change="onIDChange()"/>
    URL <input type="text" ng-model="data.url" ng-change="onManualUrlChange()"/>
</div>

//JS

angular.module('myApp',[])
.controller('MyController', ['$scope', function($scope){
  $scope.data = {
    id:'',
    url:''
  }
  $scope.manualUrl = false;

  $scope.onIDChange = function(){
    if(!$scope.manualUrl){
      if($scope.data.id === ''){
        $scope.data.url = '';
      } else {
        $scope.data.url = "http://myurl/" + $scope.data.id + ".txt";
      }
    }
  }

  $scope.onManualUrlChange = function(){
    $scope.manualUrl = true
  };
}]);

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 reason behind 'continue' not functioning properly in an Angular forEach loop?

I have a particular issue with my Angular app. I am using an angular.forEach function and trying to skip some values by using the continue keyword, but for some reason it's not working as expected. <div ng-app="app"> <div ng-controller="te ...

Make sure to wait for the VueX value to be fully loaded before loading the component

Whenever a user attempts to directly navigate and load a component URL, a HTTP call is initiated within my Vuex actions. This call will set a value in the state once it has been resolved. I am looking to prevent my component from loading until the HTTP ca ...

Creating an Account with Firebase

I've created a function called signup in my web project that uses JavaScript to add a user to my Firebase database. The function works fine, but I'm encountering an issue when I try to redirect to another page at the end of the function - the use ...

Unable to execute PHP alongside a JavaScript event listener

Using PHP, I am creating a canvas for writing and the text output will appear in a textarea (handled by other functions). There are additional input tags like a title to gather user input. The values from these input tags (title and textarea) will be submi ...

The Javascript code is failing to run following an ajax request

When I use XMLHttpRequest.send to call a php script that contains some javascript code, the javasript in the called php script does not run. The process of making the call: var formdata = new FormData(); formdata.append("uploadfilename", file); var ajax ...

Is it possible to tap into a controller's scope post transclusion?

I believe I may be mistaken, but it seems that in the firstDirective scenario, I am unable to achieve the same functionality as the secondDirective because it creates a sibling scope. This prevents me from accessing the scope of the template's control ...

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...

Fixed position not being maintained after clicking the button

Looking for some help with a fixed header issue on my website. The header is supposed to stay at the top while scrolling, which works well. However, when I switch to responsive view, click the menu button, and then go back to desktop view, none of the po ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

An abundance of AJAX requests inundating the server

While working on a straightforward AJAX request, I encountered an issue where the server is sending back 3 responses instead of just one (you can see the example in the attached image). Could someone provide insight into why this might be happening? var ...

Mastering the placement of lights in ThreeJS

Struggling for nearly half an hour now, attempting to place a pointlight at the base of my model, but achieving dismal outcomes. Not sure of the dimensions of my model, and consistently failing to accurately pinpoint the light within the scene. Thought ab ...

Divide a text containing HTML <br> element into multiple lines

How can I split a string containing HTML break tags into multiple lines and render it as multi-line in the UI? I've tried using the split method but it doesn't seem to work. Any suggestions on how to achieve this without using dangerouslySetInner ...

Effortlessly communicate events from a nested component to its parent in Vue 2

In my project, I created a base component called BaseInput.vue which accepts attributes and emits events. To easily bind all attributes, I use the v-bind="$attrs" directive. // BaseInput.vue <template> <label> <input v- ...

Finding the smallest value for each day in MongoDB using Mongoose

I have a collection in my MongoDB database called measured_data that includes entries for each day containing the fields measured_at and value. I am looking for a way to use Mongoose to find the lowest value recorded for each day. Any insights or suggest ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

Error in Next.js PDFtron Webviewer: ReferenceError - 'window' is not defined

Currently, I'm faced with a challenge in setting up a PDF viewer on my nextjs static page. Having recently ventured into Next.js, I'm seeking assistance from you guys to resolve this issue or suggest an alternative approach. While trying to imple ...

Utilizing a foundational element to automatically unsubscribe from multiple observable subscriptions

Within our Angular application, we have implemented a unique concept using a Base Component to manage observable subscriptions throughout the entire app. When a component subscribes to an observable, it must extend the Base Component. This approach ensures ...

Initiating a specialized directive for managing form controls

I've created a specialized directive to populate 3 dropdowns and manage the change event within the controller. When the dropdown value changes, I successfully capture the new value in my controller function. Now, I need to trigger my custom directive ...

Clicking 'Submit' triggers a continuous loop upon loading

I set up this form to automatically submit once the page has finished loading. However, I seem to be encountering a problem where the page gets stuck in a continuous loop of reloading. HTML <body onload="document.getElementById('filters').su ...