An effective method for linking a value from one ng-model to another is by identifying and matching a specific string

I have been tasked with binding a value to one model based on the content of another model when it contains a string that starts with "https".

For instance, there are two text fields each associated with a different model.

<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">

If I enter a value starting with "https" in the first text field, the value in modelText1 should be bound to modelText2 and maintained as bidirectional binding. This means that the second field will automatically receive the value dynamically if it starts with "https".

Answer №1

Check out this Demo example.

Preview

<div ng-controller="MyCtrl">
  <input type="text" ng-model="modelText1"> 
  <input type="text" ng-model="modelText2"> 
</div>

AngularJS Application

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

myApp.controller('MyCtrl', function ($scope) {
    $scope.modelText1 = '';
    $scope.modelText2 = '';

    var regEx = new RegExp(/^https/);

    $scope.$watch('modelText1', function (newValue) {
       if (newValue.toLowerCase().match(regEx)) {
          $scope.modelText2 = newValue;
       } else {
          $scope.modelText2 = '';
       }
    });
});

Another method (without using $watch) is to utilize AngularJS ng-change as demonstrated in this

sample fiddle.

Preview

<div ng-controller="MyCtrl">
  <input type="text" ng-model="modelText1" ng-change="change()"> 
  <input type="text" ng-model="modelText2"> 
</div>

AngularJS Application

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

myApp.controller('MyCtrl', function ($scope) {
    $scope.modelText1 = '';
    $scope.modelText2 = '';
    var regEx = new RegExp(/^https/);

    $scope.change = function () {
       if ($scope.modelText1.toLowerCase().match(regEx)) {
          $scope.modelText2 = $scope.modelText1;
       } else {
          $scope.modelText2 = '';
       }
    };
});

Answer №2

To implement the functionality described above, utilize the ng-change directive in the following manner:

<input type="text" ng-model="textInput1" ng-change="updateText()"> 
<input type="text" ng-model="textInput2">

Here is an example of how to handle this in your controller:

$scope.updateText = function() {
   if ($scope.textInput1 === 'https') {
     $scope.textInput2 = $scope.textInput1;
   else
     $scope.textInput2 = '';
};

Answer №3

Implement the ng-change directive to validate if the input text equals 'https'

angular.module('app',[])
.controller('ctrl',function($scope){
  $scope.changeItem = function(item){
   
  $scope.modelText2 = "";
    if(item.toLowerCase() === "https"){
      $scope.modelText2 = item
    }
    
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl"> 
<input type="text" ng-model="modelText1" ng-change="changeItem(modelText1)"> 
  <input type="text" ng-model="modelText2"> 
</div>

UPDATED

To prevent failure when checking for 'HTTPS', utilize the toLowerCase method to convert all characters to lowercase

Answer №4

HTML Example:

<input type="text" ng-model="exampleModel" ng-change="updateModal(exampleModel)">

JS Sample:

var exampleModel = $scope.exampleModel.toUpperCase();

    $scope.updateModal = function(){
        $scope.newModel = '';
        if(exampleModel.includes('https')!=-1){
              $scope.newModel = exampleModel;
        }
    }

Answer №5

If you are looking for a more reusable solution across multiple views, another approach could be creating a directive. This can help in keeping the controller clean and focused on controlling complex business logic and data. Check out this example on jsFiddle: http://jsfiddle.net/j5ga8vhk/7/

View

<div ng-controller="MyCtrl">
  <input type="text" ng-model="modelText1" > 
  <input type="text" ng-model="modelText2" model-listener="modelText1" model-listener-value="https" > 
</div>

Angular JS

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

    myApp.controller('MyCtrl', function ($scope) {
        $scope.modelText1 = '';
        $scope.modelText2 = '';

        });


myApp.directive('modelListener', [function()    {

    return {

        restrict: 'A',

        controller: ['$scope',  function($scope) {

        }],
        link: function($scope, iElement, iAttrs, ctrl) {

            $scope.$watch(iAttrs.modelListener, function() {

                if($scope[iAttrs.modelListener] === iAttrs.modelListenerValue ) {
                   $scope[iAttrs.ngModel] = $scope[iAttrs.modelListener];
                } else {
                    $scope[iAttrs.ngModel] = "";
                }
            }, 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

How can the md-sidenav be automatically opened when a specific ui-router state is loaded, without being locked in the open

I am facing an issue with my md-sidenav in certain ui-router states. I need it to be open in some states and closed in others, while also animating the opening and closing transitions between states. Ideally, I would like to have a function that automatica ...

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

Having a solid grasp of React and Material UI, as well as familiarity with the concept of props and

For my react application, I utilize Material UI (@mui/material). However, I've come to realize that there might be some nuances in how the components interact with each other. For instance, if I nest a MenuItem inside a Box or a Link inside a Typograp ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

Troubleshooting Karate - jbang.execute() (Node npm)

Need help with a question that's part of our project presentation. We are working on controlling the output of KARATE, ensuring it returns an OK or a KO depending on the test result. Currently, it always gives back 0 regardless of success or failure. ...

The UseEffect function is displaying an inappropriate value, however, it only occurs once

My goal is to display the state value whenever the password is changed using the useEffect hook in React. It's working fine for the password, but the issue arises when I try to change the email. The console also renders the email value, which is not i ...

Recognizing a component through various page loads

The title of this question may not be the best, but I hope my explanation clarifies what I'm trying to achieve. It's 4AM, so please forgive any confusion in my message. What I want to do is identify if a user-selected element appears on any page ...

Tips for maintaining the original ng-click initialized value as the ng-init value after the page is refreshed

My ng-repeat feature includes buttons for liking and disliking images. The problem I'm facing is that each time the page refreshes, the count of likes and dislikes gets reset to the initial value set by ng-init. How can I maintain the incremented lik ...

What is the best way to sort through this complex array of nested objects in Typescript/Angular?

tableData consists of an array containing PDO objects. Each PDO object may have zero or more advocacy (pdo_advocacies), and each advocacy can contain zero or more programs (pdo_programs). For example: // Array of PDO object [ { id: 1, ...

Is Jquery "resistant" to updating CSS properties?

Within my HTML document, there exists a div with the class fd-video-upload-box, which has the following style properties applied: background-color: rgb(236, 238, 239); outline: 1px dashed gray !important; Upon rendering, it displays correctly as intended ...

Invalid PDF File - Unable to Complete Download via $http

I'm facing an issue while attempting to download a PDF file using the $http service in AngularJS. Upon trying to open the downloaded file, I encounter an error message stating "Invalid Color Space" and the page appears blank. To troubleshoot this pr ...

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

How to Retrieve Post Data for Each Field in AngularJS

Utilizing ng-model, I can easily retrieve data from a post by assigning an ng-model value to each field and accessing it from the $scope. But what about retrieving all fields values from a post without knowing each individual field? I'm looking for ...

Activate the Jquery-ui Tooltip with a click event

Here is the code I'm using: function DrawTipsProgress(postid, ajaxurl) { var data = { action: 'ajax_action', post_id: postid } jQuery('#dashicon-' + postid).on("click", function () { jQuery.p ...

The Jquery click event refuses to trigger

Below is the JavaScript code that is not functioning: $('#change-priority-modal').find('.btn-primary').unbind().on("click", function () { //my_func_body } Interestingly, the code works perfectly fine in the developer console. I would ...

What is the process for implementing ng-required in a MultiSelect component?

When using the searchable-multiselect in angular js, I've come across an issue where ng-required=true is not working in the multiselect. Does anyone know how to apply ng-required in MultiSelect? <searchable-multiselect display-attr="name" selected ...

What is preventing the text of the elements from being updated?

My attempt to use JavaScript to change the text of this element has not been successful. The header I am trying to modify is enter image description here var elem = document.getElementsByClassName("headertext"); elem.innerHTML = "hello world"; <ul cl ...

The dot notation in JSON syntax allows for easy access

Recently, I've been struggling with referencing a variable in JSON dot notation within my meteor application. It seems that when trying to access respJson.userlower.name, userlower is not being recognized as a valid variable. Is there a workaround for ...

Issue with Angular UI tooltip not closing correctly inside ng-repeat loop

Check out the plunker link provided below for reference: http://plnkr.co/edit/RPpjULZsSDnTFPKiafl2 Essentially, I am experiencing an issue where the angular-ui tooltip persists even when moving to a position with ng-disabled set to true. Any suggestions ...

Initiate a click event on an anchor element with the reference of "a href"

I'm currently facing an issue with clicking a href element on my HTML website. The click event doesn't seem to be triggered. CODE: HTML CODE: <div class="button" id="info" ></div> <ul id="game-options"> <li><a ...