"Printed within the custom directive, the ng model value shows up as undefined

I am currently in the process of creating a custom directive that involves a simple template consisting of an input type textarea. I am assigning the ng-model to ngmodel and creating a link function where I am trying to capture the value of ngmodel. However, I am encountering an issue where it is printing as undefined. Could someone please assist me in resolving this issue? Attached is the link to the code that I have attempted to make corrections on: plunkr , and the code snippet starts here:

// Code starts here

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

app.directive('markdownEditor', function () {
  return {
    restrict: 'E',
    scope: {
      ngModel: "="
    },
    require:'ngModel', 
    template:
    '<textarea ng-model="ngModel"></textarea>' +
    '{{ ngModel}}',
    link:function(scope,ele,attr,ctrl){
      ele.on("keydown",function(){
        alert(scope.ctrl)
      })
    }
  }
});

app.controller('DemoCtrl', function ($scope) {
  var x= $scope.markdown;
});
<html ng-app="myApp">
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
    <div ng-controller="DemoCtrl">
      <h3>Markdown editor</h3>
      <markdown-editor ng-model="markdown" name="markdown"></markdown-editor>
    </div>
  </body>
</html>

Answer №1

There are a couple of issues with the current setup: you're attempting to alert the controller directly instead of the ng-model variable, and monitoring keydown events means you'll be lagging behind by one keystroke.

Consider using this approach instead:

var app = angular.module('myApp', []);
app.directive('markdownEditor', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        template: '<textarea ng-model="foo"></textarea>',
         link: function(scope, ele, attr, ctrl) {
            ele.on("keyup", function() { // (or use "change" if you don't need to check every single keystroke)
                alert(scope.foo);
            })
        }
    }
});

app.controller('DemoCtrl', function($scope) {
});

https://plnkr.co/edit/wf0NBnQqmgcwE606xeZg

(I would strongly recommend avoiding naming your variable "ngModel" -- this can lead to confusion between the variable and the ngModel directive itself.)

Answer №2

Make sure to include the scope property name like:

alert(scope.ngModel)

PS: AVOID USING ngModel as A VARIABLE NAME

// Your code should be placed here

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

app.directive('markdownEditor', function () {
  return {
    restrict: 'E',
    scope: {
      ngModel: "="
    },
    require:'ngModel', 
    template:
    '<textarea ng-model="ngModel"></textarea>' +
    '{{ ngModel}}',
    link:function(scope,ele,attr,ctrl){
      ele.on("keyup",function(){
        alert(scope.ngModel)
      })
    }
  }
});

app.controller('DemoCtrl', function ($scope) {
  var x= $scope.markdown;
});
<html ng-app="myApp">

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <div ng-controller="DemoCtrl">
    <h3>Markdown editor</h3>
    <markdown-editor ng-model="markdown" name="markdown"></markdown-editor>
  </div>
</body>

</html>

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

MERN Stack deployment to Heroku: Remote rejected - unable to push changes to master branch (pre-receive hook declined)

Just a heads up: I've successfully deployed using this method around 3 times in the past, but now it seems to be failing. Could there have been an update with Heroku that's causing this issue? Not entirely sure... I'm attempting to push my ...

Error: Unable to access the 'name' property of an undefined value. Despite my efforts, I am unable to determine the root cause of this issue. My technology stack includes mysql for the database, nodejs for the backend,

Can someone help me with a TypeError: Cannot read property 'name' of undefined error I'm encountering while trying to add new users to a MySql database using Node.js and EJS as the view engine? I've been unable to identify the cause of ...

Is there a way to use JavaScript to automatically open a URL at regular intervals?

List of URLs in JavaScript: var websites = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com']; I have an array containing multiple website URLs. My goal is to open each URL in a new tab or window e ...

Holding off $ajax requests until specific code finishes executing

I'm facing an issue with incorporating geolocation data into my $ajax call URL. Currently, both console.log(lat/lon) calls return the initial value of 0, indicating that the geolocation call is too late to provide the updated values. This results in t ...

What methods can I use to streamline integration with minimal lines of code?

Seeking help with JavaScript: Recently dived into JavaScript and managed to create the desired functionality for my navigation menu. However, I suspect that my code is not optimized as I find myself repeating lines unnecessarily. Here's a snippet of ...

The styles of a jQuery Mobile listview aren't updating properly when the list items are emptied and then dynamically re-created

When I have a listview that dynamically creates its list items using JavaScript code, everything works perfectly the first time the code runs. However, upon subsequent executions, the list is generated correctly but loses the jQuery Mobile styling. Despite ...

Retrieve the report information and present it in a HTML data table using a REST API

My understanding of REST API and Javascript is limited, but I now find myself needing to interact with a third-party company's REST API for email reporting purposes. The data can be accessed through a GET method using a URL with a specific TOKEN: {pl ...

Utilize resources from webpack's bundled npm package assets

I've been racking my brain over this issue for quite some time now, and I'm starting to wonder if it's even achievable. Any assistance on this matter would be greatly appreciated! The npm dilemma I have an npm package that serves as a coll ...

What is preventing me from loading a JavaScript script using a regular working URL?

After inserting the following line into my HTML file: <script type="text/javascript" src="http://static.citygridmedia.com/ads/scripts/v2/loader.js"></script> (whether inside or outside the <head></head> tags), I am encountering a ...

Stop unauthorized direct access to PHP forms and only allow submission through AJAX requests

I have set up a script that sends an email notification whenever someone comments on my Facebook comment box. The script uses FB.event.subscribe to trigger an AJAX call to mail.php on my server, which then sends an email to my address. How can I enhance ...

Establishing a connection with Taffy DB using Node.js

Currently, I am in the process of developing an application that utilizes Angular js, Node js, and Taffy DB. The main challenge I am facing involves storing the data submitted from the front-end into Taffy DB through the Node js server. var express = req ...

Schema-based validation by Joi is recommended for this scenario

How can we apply Joi validation to the schema shown below? What is the process for validating nested objects and arrays in this context? const user = { address: { contactName: 'Sunny', detailAddress: { line1: & ...

Updating an image using AJAX and Flask

I have a situation in HTML where I need to constantly update an image file with the latest images that come in. Below is the Flask code snippet: @app.route('/uploads/update_file', methods=['GET', 'POST']) def update_file(): ...

Display all y-axis values in the tooltip using HighCharts

I utilized a chart example from http://www.highcharts.com/demo/column-stacked When you hover the mouse over a column, it displays the value of the y axis being hovered and the total value. I am interested in having the tooltip show the values of all 3 y ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

Why are JS & jQuery's inArray() and indexOf() functions not functioning correctly when indexes are strings?

Here is an example of an array: var arr = []; arr['A string'] = '123'; arr['Another string'] = '456'; I am attempting to find the index of either '123' or '456'. Both methods below are returnin ...

Turn an existing string into a new string where each character is changed to an asterisk, and spaces remain as spaces

I am attempting to create a new string from an existing string using javascript. In the newly generated string, all characters except for spaces would be represented by '*'. For instance, if the original string is "hide me" then the resulting ...

Node.js Project Using a Specific URL and Parameter

Two things are on my mind: 1. I'm trying to set up my project's URL as 127.0.0.1:8080/param=id, but I've been unsuccessful so far despite attempting the following: app.get('/param=id', function(req, res) { console.log(req.param ...

I'm wondering why myDivId.toggle() is functioning properly but myDivClass.toggle() is not working as expected

Using JQuery's toggle() function, I have been able to hide and show some DIVs successfully. Recently, I discovered relationships between certain DIVs that allowed me to group them into a class. I decided to try toggling the entire class rather than ...

Need to `come back` multiple times

I am facing an issue where I want to return multiple lines, but only the first line is being returned. I attempted to create a function specifically for returning the line, but encountered errors because I couldn't figure out where to place it. Does ...