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

Is there a way to modify a specific key value in all embedded objects using Mongoose?

I'm currently working on a chat application and I'm facing a challenge with implementing the 'seen' functionality. I need to update all chat messages in the database by setting the 'seen' column to true. Here is the schema st ...

In the absence of a value

In my code, I've implemented a functionality that saves the user's input into local storage and displays it in a specific ID. However, I want to make sure that if the input field is left empty, the user is prompted to enter their name. function ...

javascript display an alert when the page is loaded

My customer wants to display an alert upon visiting a website. The problem is, alerts pause the page loading until the user clicks "Ok," and the client needs the page to continue loading in the background while the alert is visible. We could create a cus ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

Crafting an interactive saturation effect for mouseover interactions in a circular design

I'm looking to create a unique hover effect for my images. I have both a desaturated version and a full color version of the same image. My idea is to have mousing over the desaturated image reveal a circle spotlighting the color version underneath, a ...

Do you need to define a schema before querying data with Mongoose?

Is it necessary to adhere to a model with a schema before running any query? And how can one query a database collection without the schema, when referred by the collection name? This scenario is demonstrated in an example query from the Mongoose document ...

Ways to display additional text with a "Read More" link after three lines of content without relying on a

I am currently working on an application where I need to display text in a limited space of 3 lines. If the text exceeds this limit, I want to show either "Read More" or "Hide". Below is the code snippet that I am using for this functionality. class Cust ...

How to Ensure Screen Opens in Landscape Mode with Phaser3

https://i.stack.imgur.com/keCil.pngIn my Phaser3 game, I am trying to achieve the functionality where the game opens horizontally in a webview without requiring the user to rotate their phone. The vertical photo below shows the game in its current state. W ...

Enhancing Real-time Communication with NodeJS and NowJs Servers

Recently, I stumbled upon NodeJS and NowJS and I'm fascinated by the technology. My goal is to develop a Facebook-style instant commenting application where users can post comments that will instantly appear on the feed. After watching the screencast ...

Selecting Texture Coordinates

My goal is to pinpoint where a user has clicked on a texture of an object to trigger a response by redrawing the texture. I've been able to achieve this by rendering my objects with a color-coded texture onto a separate render target and using gl.rea ...

What is the best way to apply the active class using ng-click?

Here is an example of code I am working with: <div class="account-item"> <div class="account-heading" ng-class="active"> <h4 class="account-title"> <a href="#/Messages" onclick="SetActiveAccountHeading(this);" ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

Angular Grunt minification encountered an unexpected punctuation token «}», when it was expecting a colon punctuation «:»

Given that 'id' is a pre-defined dynamic variable, what could be causing it not to minify correctly? let dynamicVar = 'device_' + id; $scope[dynamicVar] = {dynamicVar}; This is the specific error message from grunt-contrib-uglify: ...

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...

Exploring the differences between objects in AngularJS

My goal is to have comments displayed if a Post contains them. I attempted to use angular.equals, but it doesn't seem to be working for me. Maybe I'm not using it correctly? Below is the Controller code for both Post and Comment. var PostContro ...

How to effectively inject moment.js dependency into AngularJS?

In my app.js file, I've defined my app module like this: var myApp = angular.module('myApp', ['angularMoment']); Next, in my controller, I'm trying to use the moment() function: myApp.controller('myComtroller', [& ...

Is it advisable to incorporate vue-resource in Vuex actions?

I am currently working on a web application that retrieves airport data from the backend. To manage states and data sharing, I am utilizing Vuex. My dilemma is whether to load the airports in my Vuex actions or within a method of my Vue instance which will ...

Tips on showcasing a nested array in Next.js or converting it into an object

{ "count": 2, "rows": [ { "id": "5ab46e31-391c-46a7-8e45-db9ada07626d", "name": "admin", "email": "<a href="/cdn-cgi/l/email-p ...

Sharing NPM Scripts Via a Package to be Utilized by Project upon Installation

I have streamlined my linting setup by consolidating all configuration and related packages/plugins/presets (for prettier, stylelint, eslint, commitlint) into an npm package. This allows me to utilize the same setup across multiple projects, simply extendi ...

The error in React syntax doesn't appear to be visible in CodePen

Currently, I am diving into the React Tutorial for creating a tic-tac-toe game. If you'd like to take a look at my code on Codepen, feel free to click here. Upon reviewing my code, I noticed a bug at line 21 where there is a missing comma after ' ...