Passing ngModel from controller to directive in AngularJS

I'm currently working on a project that involves a controller with an attribute directive nested inside of it. This directive requires access to the ngModel of its parent controller.

For more context, feel free to check out this Plunkr.

Issue at Hand

Although the form seems to load properly, the console log within the directive is showing:

a.$…t.aa {$attr: Object, $$element: R[1], fieldValidator: "", boundModel: "person", ngModel: undefined}

Can anyone shed light on why the ngModel is coming up as undefined and why the boundModel is displaying 'person'? I've been staring at this for too long without any breakthrough...

Answer №1

give this a shot

app.directive('fieldValidator', [function(){
  return {
    restrict: 'A',
    scope: {
      boundModel: '='
    },
    controller: function($scope){

    },
    link: function ($scope, $elem, $attrs) {
      console.log($scope.boundModel);
    }
  }
}]);

as others have mentioned, make sure you have an ng-model set up when using this directive. boundModel: '=' is the same as boundModel: '=boundModel'

If you want to access boundModel, simply use $scope.boundModel and don't worry about what's shown in $attr; that might not be what you're looking for.

Answer №2

{ data: '=model' } indicates that you transfer the data property via the model attribute. However, in a template, you will not find the model attribute. Instead, it is named data-model.

Answer №3

scope: {
   boundModel: '=ngModel'
},

Your usage of scope variables is incorrect. By specifying '=ngModel', you are indicating that there is an attribute named 'ng-model' on the directive, which should be accessed as scope.boundModel within the directive.

It appears that you want to utilize the ng-model controller. In that case, why not simply use ng-model directly on your directive instead of creating a new variable like boundModel?

To achieve this, you can rename the bound-model in your HTML to ng-model and remove the scope from the directive. If you intend to utilize the ngModelController, you'll need to inject it within the directive's link function as shown below:

return {
    restrict: 'A',
    required: '^ngModel',
    scope: {},
    controller: function($scope){

    },
    link: function ($scope, $elem, $attrs, ngModel) {
      console.log($attrs);
    }
  }

By using the ngModelController, you can then manage validity and other aspects for the data bound to ng-model in the HTML, as outlined here.

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

Validation of forms using Javascript

I currently have an HTML form with JavaScript validation. Instead of displaying error messages in a popup using the alert command, how can I show them next to the text boxes? Here is my current code: if (document.gfiDownloadForm.txtFirstName.value == &ap ...

Unable to turn off X-Powered-By: Express

After attempting to use app.disable("x-powered-by"); without success, I came across some helpful posts on the topic: how to remove X-Powered-By in ExpressJS Can't get rid of header X-Powered-By:Express I am using "express": "^4.16.4" as backend a ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

What is the proper way to safely close the pg-promise connection in a node.js environment once all jest tests are completed?

I am facing a challenge in closing a PG-Promise database connection after running a function test in Jest. The database connection is initialized in one central location (db.js) and required in multiple places. In this scenario, it is being used by seed.j ...

Whenever I find myself being redirected to the login page, my goal is to eliminate the bottomTab from view

I'm looking to eliminate the bottom tab when I land on the login page, even though I've set it up for all pages. However, whenever I click on the login button, the tab remains visible. Here is my current code: import React, { useContext } from & ...

`Evaluating the functionalities of AngularJS using Protractor`

Currently, I'm in the process of developing an AngularJS app and have been tasked with incorporating automated testing into our workflow. This is a new concept for me, so it's taking some time to fully grasp. After much consideration, I've ...

Concerns arise with jQuery grid compatibility in Firefox browsers

I have found an interesting tutorial on draggable image boxes grid at this link. Although everything is functioning properly, I am encountering an issue with the drag function specifically on the home page when using Firefox. As a beginner in jQuery, I am ...

What steps should I take to ensure a local HTML page retains the current section that is hidden open whenever it is reloaded?

One of the challenges I have encountered with my local HTML note-taking file is that, despite dividing it into hidden sections accessible by clicking on buttons at the top of the page, reloading the content resets it back to its default state. This means t ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

How do I create a notification when the div reaches 100% alignment on the left side using Javascript?

Is there a way to receive an alert when the div with the class name "earth" reaches 100% on the left side, without using jQuery? I attempted to utilize setTimeout but I am looking for an alternative method that does not rely on time, but rather on positi ...

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

tips on launching a pre-existing react native project

Trying to run a project downloaded from someone else can be quite challenging. I encountered some issues where the project just wouldn't start, and now I'm completely stuck. Can anyone help me out? https://github.com/sunlight3d/react_native_v0.4 ...

The component fails to update even after changes are made to the Redux state

I currently have 4 buttons, each with a different color, and I want to display the last 10 button clicks as colors on 10 squares. The redux state is being used to map and display the square colors, which are also stored in localStorage. When a button is c ...

Unable to get the code for automatically refreshing a DIV every 5 seconds to function properly

My Inquiry Regarding DIV Refresh I am having issues with the code below that is supposed to automatically refresh the DIV id refreshDiv every 5 seconds, but it is not working as expected. <div id ="refreshDiv" class="span2" style="text-align:left;"&g ...

Version 5 of Material UI has a bug where the Grid component does not properly stretch

How can I make the Grid component stretch when one of the Card components contains extra text? You can view the sample code here. Changing the alignItems property to "flex-end" or "center" works, but when using alignItems: "stretch" it does not work. I ...

Having difficulty adding a custom service to the run function in an AngularJS application

Just getting started with AngularJS and I've set up my app.js with a run function. I created a custom service called coreService that I need to inject into the run function, but I keep encountering an error. The error message says: Error: [$injector: ...

Using Google Apps Script to upload a text file to Google Drive

It seems like uploading a file should be straightforward. However, I'm struggling with understanding blobs. function createFileUploader() { var app = UiApp.createApplication(); var panel = app.createVerticalPanel().setId('panel'); v ...

To show the image along with the .titleclass, .subtitleclass, and .description when clicking on it, what steps do I

<?php while($galleryrec = mysqli_fetch_array($getresultgallery)){ ?> <div class="col-lg-2 col-md-2 mb-4 mb-lg-0" id="imageidback"> <img data-id ="<?php echo $galleryrec['publishid& ...

Unable to modify the logo images in React

I'm struggling to figure out how to make my images (favorite.svg and favorite-white.sgv) change every time the button is clicked in React. I've tried various solutions but it's proving to be quite challenging. When the button is clicked, I ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...