Assigning the directive value to the ng-model variable in AngularJS

Hello! I am currently working on creating a directive to pass a value to my ng-model. Within my directive, there is a controller and I would like to pass the value from it to my ng-model.

Let's assume I have a string value, when I click on $scope.speakUP, it should be passed onto the ng-model.

.directive('speak', function(){
          return {
            restrict: 'A',
             require: 'ngModel',
            scope: true,
            template: '<i ng-click = "speakUP()" class="icon ion-mic-a larger"></i>',

            controller: function($scope, $element){
             $scope.speakUP = function(){

                     $scope.passThisString = "Sample Data";

                 }

        }

Here is my HTML code:

  <input type="text" ng-model="sampleModel" speak>

Answer №1

Here is a simple illustration to help you get started on achieving your objectives.

 app.directive('inputField', function () {
    return {
        require: '?ngModel',
        template: '<input ng-model="value" ng-change="onChange()"><i ng-click="speakUP()" class="icon ion-mic-a larger">click</i>',
        link: function ($scope, $element, $attrs, ngModel) {
            if (!ngModel) return;

            $scope.speakUP = function(){
              ngModel.$setViewValue('your data');
              ngModel.$render(); 
            }

           $scope.onChange = function() {
             ngModel.$setViewValue($scope.value);
           };

           ngModel.$render = function() {
             $scope.value = ngModel.$modelValue;
           };
        }
    };
});

HTML

<input-field name="sampleModel" ng-model="sampleModel"></input-field>

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

Prevent the running of JavaScript events initiated by a script fetched through AJAX

In my JS application, I am using AJAX to load different parts of the application. After the AJAX function is completed, the corresponding script is executed. However, I am facing an issue when trying to load a new part of the application. I need to find a ...

Passing Data from Child to Parent Components in ReactJS

I'm new to React and JavaScript, currently working on a website. I've encountered an issue with passing data between components from child to parent. Here's the scenario: In my App.js script, I'm using react-router-dom for routing. I ...

Schema of type Mongoose

Can anyone provide some guidance on working with Mongoose and implementing a type schema? I am trying to create users with specific roles. This is my user model: const userSchema = mongoose.Schema( { _id: { type: String, default: rando ...

Notification box appears only when closing the window, not when reloading the page

I've been trying to find a way to remind my users to log out before closing the window. I found this code that seems to work: window.onbeforeunload = confirmExit; function confirmExit() { return "It's best to log out before you close this pa ...

Error notification in Expess: Unhandled Promise Rejection

const Vehicle = mongoose.model('Vehicle', new mongoose.Schema({ type: { type: String, required: true, } })); router.patch('/:id', async (req, res) => { const { validationError } = customValidator(req.body); if (val ...

Jest's testing coverage does not include branch coverage

I've been working on creating a unit test for my API and have put in every possible test I could come up with. However, when running jest for coverage, I am still not getting 100% coverage. The report indicates that certain statements, branches, and l ...

When utilizing PassportJS, SequelizeJS, and JWT tokens, req.user may be found to be undefined

Despite searching various answers on Stackoverflow and consulting the documentation, I am still unable to identify what might be causing the issue. Within my application, I am utilizing SequelizeJS to interact with my MySQL database and now attempting to s ...

Deploy a web application using JavaScript and HTML to Heroku platform

I noticed that when I visit the Heroku dashboard, there is an option to create an app using Node.js, but not JavaScript. This raises a question for me - if I want to upload my locally created JavaScript/HTML5 app to Heroku, do I need to select Node.js or ...

Updating the DOM after moving an array item using Vue's `splice` method seems to be causing some issues

Attempting to shift a specific item in an array, located at position x, to position 2</code. Although the code below successfully accomplishes this task of relocating the item, Vue fails to update the <code>DOM. This is the snippet of code being ...

A single click causes the entire row of cards to extend seamlessly

The cards on this tab were generated using a loop and the data is sourced from a database. When I click on the "Show More" button, the entire visible column expands along with it. The expansion does not reveal the content immediately; instead, the content ...

Calling JavaScript functions from ASP.NET code-behind

A question has been updated. Reference: The following HTML link "Add Regular" is functioning correctly. When clicked, it displays the notification showing that the related .js and .css files are working. HTML Link <a href="#" id="add-regular">Add ...

Utilizing npm scripts to compress all HTML files within a directory, including its subdirectories

I am looking for a way to compress all the files with a .html extension in a particular folder, including any subfolders, using a script called npm run. Ideally, I would like the original .html files to be replaced with the minified versions, but creating ...

Struggling to figure out the correct way to use User.findOne({ userID: searchUserID }? I'm not receiving a return value at

Currently, I am facing some issues while trying to implement an update/put functionality in my node.js project. I am a beginner in JavaScript and have no idea where the problem is originating from. I am using express, MongoDB, and mongoose. The problem se ...

Is the page reloading automatically after updating the innerHTML content?

Trying my hand at creating a JavaScript/HTML page that automatically generates an audio player when provided with a URL. However, every time I click the generated button, the audio player is inserted but then disappears as if the page is refreshing. Here ...

Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is pressed. .directive("car", function(){ return { restrict:"A", link:func ...

Transmitting a feature identifier: darkened display

My goal is to pass an attribute variable with three.js to the vertex shader, which then should transfer it to the fragment shader using a varying variable. Here's the Vertex Shader: attribute vec4 color; varying vec4 outColor; void main() { ...

I'm experiencing a connection issue despite using the same call file. Why could this be happening?

Here is my situation: I have developed a WebSocket Server using Node.js within an environment primarily based on Laravel. To mimic the functionality of Laravel's .env file, I have incorporated the dotenv package. Recently, I came across a strange obs ...

Leveraging TypeScript's declaration file

Greetings! I am currently facing an issue while utilizing a declaration file in my TypeScript project. Here is the declaration file that I am working with: // Type definitions for Dropzone 4.3.0 // Project: http://www.dropzonejs.com/ // Definitions ...

Guide to converting a specific tag into div using Javascript

I am working with some HTML code that includes a div: <div class="myDiv"> <a href="" title="">My link</a> <p>This is a paragraph</p> <script>//This is a script</script> </div> Additionally, I ha ...

Sending the HTML variable to an Angular function

I'm running into an issue where I need to pass a Handlebar HTML variable to a scope function using Angular. If I try passing it as function('{{variable}}'), the function receives the variable literally as "{{variable}}". But if I use functio ...