ways to access ng-model value within a directive

I recently developed a custom directive in AngularJS that utilizes the input type number with min-max and ng-model attributes. I made sure to use an isolated scope for the directive. However, despite setting up a blur event within the directive, I am encountering issues retrieving the ng-model value:

<input my-directive min="5" max="10" ng-model="num" type="number">
myApp.directive('myDirective', function () {
  function link($scope, ele, attr) {
    $scope.$watch('num', function (value) {
      console.log(value);
    })
    ele.on('blur', function () {
      console.log($scope.num, $scope.min, $scope.max);
    })
  }
  return {
    restrict : 'A',
    scope: {
      num: "=ngModel",
      min: "=?",
      max: "=?"
    },
    link: link
  }
});

output: undefined 5 10

I'm puzzled as to what I might be missing. Any suggestions?

Answer â„–1

To avoid using a binding with ngModel, include it with the require method and inject it into the link function:

myApp.directive('myDirective', function () {
  function link($scope, ele, attr, ngModel) { // <--- Injecting
    $scope.$watch(() => ngModel.$viewValue, (n, o) => {
      // Watching `ngModel.$viewValue`
      console.log('WATCH', n, o);
    })
    ele.on('blur', function () {
      // `ngModel.$viewValue` is the current value
      console.log('BLUR', ngModel.$viewValue, $scope.min, $scope.max);
    })
  }
  return {
    require: 'ngModel', // <--- Requiring 
    restrict : 'A',
    scope: {  // <--- Removing `ngModel` binding from scope
      min: "=?",
      max: "=?"
    },
    link: link
  }
});

Check out this demonstration

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

Utilize Google Autofill to easily populate address fields in a form

I've come across several autofill address codes, but I'm looking to integrate a Post function that would allow me to post the obtained data to a PHP page. Is there anyone who can assist with the javascript or HTML code to achieve this? HTML Cod ...

Express JS is experiencing difficulties with the functionality of the iframe

When I'm using iframe in HTML, it works perfectly fine: <iframe src="main.html" height="100px"></iframe> But when I use Iframe in Express, it shows an error: <iframe src="main.html" height="100px&qu ...

What is the best method for uploading images and form content simultaneously in a Vue application?

How can I simultaneously upload images and form content? Is it possible to upload both to the client first and then to the server together with the form content? I'm looking to submit the form content along with the image to the server in one go when ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Guide on preventing selection with beforeSelectionChange when using the select All checkbox in ng-grid

When the select All checkbox in the header is clicked, the beforeSelectionChange function is called with a rowItem array. Unfortunately, there doesn't seem to be an option to disallow selection. I need to disable the checkbox for certain rows based on ...

Having issues with ng-view in AngularJs - it's not functioning properly

I am having trouble with the ng-view directive not working. When I implement it, all I see is the "Page" title. Can someone help me diagnose the issue? https://jsfiddle.net/dsgfdyp1/3/ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/b ...

Cipher Caesar - symbols and additional characters

I've constructed a Caesar Cipher script down below, however, I wish for the output string to contain spaces and other characters. Despite my attempts with regex, it doesn't seem to rectify the issue or maybe I'm not utilizing it correctly †...

Exploring the differences between selecting an element by its class and making multiple calls to select elements

I have a question about choosing multiple elements from a page. Is it better to use a selector by class, or make multiple calls using the selector by id? The number of elements I want to select, or unwanted elements that need to be checked by the selector ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

Ways to transfer information from an axios API to a state in React

I am currently working with an API that consists of an array of objects. My goal is to pass this data into a state in order to display it within a component on a website. First Approach: // Fetches the API data const newData = axios.get(url).then( ...

Common mistakes encountered when utilizing webpack for react development

I'm currently following the exercises in Pro MERN Stack by Apress and have come across a webpack issue. Everything was running smoothly until I introduced webpack into the mix. Now, when I execute npm run compile, I encounter the following error: > ...

Is there a way to integrate Javascript code with a React component?

I need to find a way to include this block of code in just one specific React component. Any suggestions? <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button sty ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

Incorporating filters within ui-sref for enhanced functionality

After coming across this answer, I realized it doesn't address my specific issue. My goal is to have the complete state name generated by my filter, rather than just using the filter for state parameters. Is there a way to use a filter to generate th ...

Transform PDF files into PNG format directly in your web browser

I am currently utilizing Vue.js and attempting to convert a PDF file to PNG or another image format directly within the browser. My current setup involves reading the PDF from a URL using PDF.js along with the Vue.js component pdfvuer. let instance = this ...

Using jQuery to iterate through JSON data obtained from a web service

In this code snippet, I am attempting to retrieve a JSON response from a PHP page and then iterate through it to display the name field of each JSON object. However, for some reason, nothing is being alerted out. <html> <head> <title>A ...

`Storing modified PDF containing interactive form elements using integrated Chrome viewer and transferring it to a remote server`

Our current setup utilizes the default embedded Chrome PDF viewer to showcase a PDF document with interactive form fields, enabling users to conveniently fill out the form. Once completed, they can click on the download button to save the form with or with ...

Express - An error occurred: Unable to access the property 'prototype' as it is undefined in the file request.js on line 31

My time has been consumed trying to troubleshoot this issue, yet I am puzzled by its origin and the reason behind this error. I am in the process of creating a basic website to hone my skills in React and have been attempting to retrieve data from Riot&ap ...