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

Leveraging ng-model to bind a variable retrieved from a service

I've encountered a challenge with angular that I'm struggling to solve. I developed a CMS that allows product owners to create a dynamic registration form, which is then converted into JSON through an API. On the app side, I am using angular to ...

What is the best way to toggle a d3 svg overlay using a leaflet layer control?

I am looking for a solution to place 3 d3 svgs on a leaflet map and control them as easily as leaflet layers. Check out this code example, which works but is not ideal. The key part is from line 75 onwards, where I create a custom layer control linked to ...

Executing an AJAX request with a specific state in Node.js

Instead of rendering add.jade directly, I have chosen to enhance the user experience by making an AJAX call to the endpoint. This allows me to maintain the URL as localhost:3000/books, rather than localhost:3000/books/add which lacks navigation state for ...

Issues with synchronizing Firebase and Node.js?

https://i.stack.imgur.com/3fwRO.png Here is the code snippet I used in my Node.js application: for(var v in sna.val()){ console.log("each "+va); console.log(v); var fourthRef = ref.child(val+'/reservation/&apos ...

switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue: let bulbImage = $.querySelector(".bulb-image"); let turnOnOption = $.querySele ...

Ensuring Consistent Visual Harmony Across Linked Elements

As part of my project developing an iPad app with PhoneGap and jQuery Mobile, I am looking to incorporate a preview pane within a carousel. This preview pane should display smaller versions of the other panes scaled inside it. The panes are dynamic and upd ...

Ways to show text in a password field

I'm looking to have the password field on a page. I'd like to show the text "Enter password" on the screen before the user starts entering their password, but once they focus on the field to enter their password, it should switch back to password ...

A Vue button that toggles between three states depending on the value in an array

In my Vue project, I am working on loading an array when the page loads. I need to check the status of each line item in the array and display a specific button for each status using a 3-way toggle. Although I believe I understand the main concept, I am s ...

Toggle the visibility of an element with a single button click

Below is a snippet of my sample code: SAMPLE HTML CODE: <ul> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <l ...

Is it possible to trigger an event for only one connected client instead of broadcasting it to all clients using socket.io?

I am seeking a way to send an event to just one connected client, rather than broadcasting it to all clients using io.emit(). ...

Unable to cancel the RTK query request

It's quite a dilemma. I need to handle the request differently when there is no user present. I've attempted different approaches like this and that const { data: carts = [] as ICart[], isFetching } = api.useGetCartProductsQuery(user.id, { skip: ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

Whenever a user navigates back to a specific page in Ionic by clicking the back button, make sure to set a variable to null

I've been attempting to set a variable as null whenever a user clicks the back button after signing in. However, my current approach doesn't seem to be working, as the variable still appears on the sign-in page. var currentUserNow = localStorage ...

Update the color scheme of text labels and the title on a 3D bar graph created with amcharts

After creating a 3D stacked bar chart, I have successfully generated the graph using the provided code. However, I am looking to customize the appearance by changing the font color of all labels and the title to a different color. While I was able to mod ...

relocate the figcaption below the image on mobile devices

Currently, I am in the process of updating an old website to make it responsive, and I have encountered several challenges along the way. My goal is to have the fig captions displayed on the right side in the desktop version, but underneath the figure in ...

Exploring the integration of two-way binding with Angular and Polymer web components

I recently stumbled upon a blog post by Seth Ladd showcasing Dart code implementation with Angular and Polymer for data binding. However, I am on the lookout for an alternative solution. Are there any other projects combining Angular and Polymer that offer ...

Is it possible to utilize $save as $add in Firebase with Angular Fire?

Is it possible to utilize $save instead of $add in Firebase object for adding data? ...

Using EJS to Render a Function Expression?

Has anyone been able to successfully render a function call in express using EJS? Here's what I've tried so far: res.render("page", { test: test() }); Can someone confirm if this is possible, or provide guidance on how to call a function fr ...

Transitioning from one CSS id to another during page loading

Wondering how to fade in one CSS id on page load and then smoothly transition to another after a few seconds? Here are the ids: #background { background: url("images/am_photography_bg.jpg") no-repeat center -25px fixed; background-size: 100%; ...

The ng-repeat directive is specifically designed to loop through a List object, and does not support iterating over Iterable

It appears that ng-repeat only works with Lists and not other types of iterables. For example, the following code does not produce the expected result: <span ng-repeat="i in [1, 2, 3].toSet()>{{i}}</span> An exception is thrown at package:an ...