extract the ng-model data and send it to an angular directive

In my current project, I have a specific situation where there are multiple text-boxes and when any of them is clicked, the corresponding ng-model should be displayed in the browser console. To achieve this functionality, I came up with the following AngularJS code:

<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.0/angular.min.js"></script>
<script>
    var app = angular.module("myApp", [])
    app.controller("myAppCtrl", function($scope){
        $scope.modelName = '';
    });
    app.directive("myDirective", function(){
        return{ 
            restrict: "A",
            link: function(scope, elem, attrs){
                scope.customFunc1 = function(){
                    console.log(attrs.ngModel);
                    scope.modelName = attrs.ngModel;
                };
            }

        }
    });
</script>
</head>
<body>
<div>
<input name="tb_1" type="text" ng-model="tb_1" ng-mousedown="customFunc1()" my-directive>
</div>
<div>
<input name="tb_2" type="text" ng-model="tb_2" ng-mousedown="customFunc1()" my-directive>
</div>

<div>
<input name="tb_3" type="text" ng-model="tb_3" ng-mousedown="customFunc1()" my-directive>
</div>
</body>
</html>

I'm facing two challenges that I need help with: 1) Whenever I click on any text-box, the ng-model of the third text-box is shown, regardless of which one I actually clicked. Can someone suggest a solution to this issue?

2) Are there alternative methods or best practices for achieving the desired functionality described above? Your insights would be greatly appreciated.

Answer №1

The issue lies within your directive, as it is currently using a single scope.

To resolve this problem, you should modify your directive to utilize an isolated scope by including scope: true inside the directive. For greater flexibility, I recommend making the ngModel attribute mandatory by using require: 'ngModel', as your directive heavily relies on it. By setting the field as required, you will have access to the ngModel in the directive's pre/post link function. This allows you to manipulate the value of the ng-model variable or perform validation at any time.

Your Directive Setup

app.directive("myDirective", function() {
  return {
    restrict: "A",
    require: 'ngModel',
    scope: true,
    link: function(scope, elem, attrs, ngModel) {
      scope.customFunc1 = function() {
        console.log(attrs.ngModel);
        scope.modelName = attrs.ngModel;
      };
    }
  }
});

See Demo on Plunker

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

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Oops! There seems to be an error with the <path> attribute. It looks like we were expecting a number, but received something different: "

I'm currently working on creating a basic line graph using d3.js and integrating it into a React component. However, I'm encountering this error: Error: <path> attribute d: Expected number, "MNaN,36.393574100…" Unfortunately, the similar ...

Conditional rendering is effective for displaying a form item based on certain conditions, but it may not be as effective for

I want a textarea element to appear or disappear based on the selected state of the radio buttons before it. If "no" is chosen, the textarea will be hidden, and if "yes" is chosen, the textarea will become visible. <fieldset class="input-group form-che ...

Transform a delimited string and an array of objects into a new format

Is there a way to easily convert a delimited string into an array of objects with data binding functionality? ng-list is suitable for arrays of strings. However, I have an array of objects where I want to delimit the text property for easy editing. Works ...

Javascript Library Issue: "Implicitly Declared Type 'Any' Error"

I am currently in the process of developing a JavaScript library that will interact with an API. My goal is to create a module that can be easily published on npm and utilized across various frameworks such as Angular or React. Below is the code snippet fo ...

Leveraging the power of AWS API Gateway and Lambda for seamless image upload and download operations with Amazon

I have successfully created a lambda function to handle image uploads and downloads to s3. However, I am encountering difficulties with the proxy integration from the API Gateway. Despite reviewing the documentation and looking at this specific question ...

Troubleshooting Node.js and Express: Adding to array leads to displaying "[object Object]"

As a newcomer to web development and currently enrolled in a course for it, I am in the process of creating a test web server before diving into my main project. In this test scenario, my goal is to extract the value from a text block and add it to a respo ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

Unexpected outcomes in linq.js

Hey there, I have a JSON object named "Faults" that looks like this: "Faults":[{"RoomId":1,"ElementId":173,"FaultTypeId":1,"Count":1,"Remark":""},{"RoomId":3,"ElementId":211,"FaultTypeId":7,"Count":1,"Remark":""},{"RoomId":4,"ElementId":173,"FaultTypeId": ...

Using json_encode with chart.js will not produce the desired result

I am attempting to utilize chart.js (newest version) to generate a pie chart. I have constructed an array that I intend to use as the data input for the chart. This is the PHP code snippet: <?php if($os != null) { $tiposOs = array('Orçamento ...

Having difficulty sending variables to onreadystatechange

Here is the latest version of the source code: var xhttp = new XMLHttpRequest(); function passVars(var1, var2, var3) { if (var1.readyState == 4) { if (var1.status == 200) { var data = var1.responseText; if (data) { playSuccess ...

The updates made to a form selection using Ajax do not reflect in jQuery's .serialize or .val functions

When using the .load jQuery function to retrieve a form and place it in the document body, I encounter an issue. After loading the form, I manually change the select value and attempt to save the form using an ajax .post request. However, when trying to ...

Iterate through an array to dynamically generate a variable number of table rows

I have experience using ng-repeat to generate a dynamic number of table cells, but how can I achieve the same result with table rows? I am working on developing a jeopardy-style game where each column should have a number of table rows equal to the number ...

What is the best way to automatically add a date and timestamp to every new entry?

I am currently working on a project that utilizes AngularJS and Ionic frameworks. The main feature of the project will involve users inputting data to create a list, and allowing any user to comment on each item in the list. One challenge I have encounter ...

Attempting to implement a disappearing effect upon submission with the use of JavaScript

I am currently working on implementing a disappearing form feature for a small web application. The idea is that once the initial form is submitted, it will be replaced by a new form. While my current code somewhat works, it only lasts for a brief moment b ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

What is the best way to allow JavaScript to access a Laravel asset?

Currently, I am working on creating a slideshow and have implemented a navbar.js file with the following code: images[0] = "{{ asset('cover/deanna-j-3GZlhROZIQg-unsplash.jpg')}}"; images[1] = "{{ asset('cover/kevin-laminto ...

What could be the reason for the onmessage listener not handling the initial SSE event?

When a client connects to a Node Express server, it creates a new EventSource. The server sends an SSE event upon initial connection and then at a 30-second interval thereafter. Strangely, the client's onmessage handler does not respond to the initial ...

Submitting a Form with an Array using AngularJS - HTTP POST

I have a situation where I need to make a POST request with an array of values in a form. Below is the HTML code I am using: <label>Name</label> <input type="text" name="name" ng-model="vm.model.name"> <label>Behaviours</label ...

Obtaining the desired element from a function without relying on an event

Recently, I've been working on a sidebar with several links <sidebar-link href="/dashboard" icon="HomeIcon" :is-active="isActive()" /> <sidebar-link href="/test" icon="TestIcon" :is-active=&qu ...