Passing ng-model data from a directive component to a controller in AngularJS

My inspiration from angular ui has led me to create a front-end library made up of components, all as angularjs directives. This allows users to easily implement directives with specific configurations and achieve the desired component results.

Here is an example of how the directive will appear:

<date-picker 
    date-format="MM.DD.YYYY HH:mm" 
    enable-navigation 
    date-picker-id="datetimepicker2"
    date-picker-model="myModel1">
</date-picker>

The concept for usage involves wrapping it in a user-created controller, which can access the directive scope like this:

<div ng-controller="myController">
   <date-picker 
         ...
       date-picker-model="myModel1">
   </date-picker>
</div>

(I use component-name-model because the component directive template may have multiple models) The code in the controller would look like this:

angular.module('myApp').controller('myController',['$scope', function($scope) {
     $scope.myModel1; //this scope binds to the datepicker template scope 
}]);

As I am new to angularJs, I have a couple of questions:

  1. How can I make the controller access the directive scope using this syntax? It seems that the controller is not recognizing the directive scope (see my code in plunker).

  2. Currently, I am facing an issue with passing the model to the template. In the directive, I have defined date-picker-model="myModel1" and then the directive will retrieve the attributes and pass them to the template like this:

    if('datePickerModel' in attrs){
         $scope.datePickerModel = attrs.datePickerModel;
    }
    

    When I use expressions on the templateUrl, ng-model="{{datePickerModel}}" does not work.

The code is quite lengthy, so I recommend checking out my plunker for a better understanding.

Thank you :-)

Answer №1

To establish a 2-way binding between the controller and the directive's scope, familiarize yourself with the scope parameter when creating your directive.

Take a look at this example for reference.

<my-customer info="igor"></my-customer>


angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
  $scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerInfo: '=info'
    },
    templateUrl: 'my-customer-iso.html'
  };
});

For more information, visit the AngularJS directive guide.

Make sure to note the usage of the symbols '=' or '@' at the beginning!

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

React NextJS: Unable to retrieve cookies or properties post redirection

Within my nextJS application, when a user logs in on the login page, a cookie is created with a token and then they are redirected to the main page which utilizes the main component. However, within the Main component, I am encountering an issue where the ...

Getting information from MongoDB using Node.js and Angular

Currently, I am facing difficulty in retrieving data from MongoDB (I'm also using Mongoose) and sending it to Angular in order to populate the ng-repeat list with the retrieved data. I have managed to either display the data on a blank page directly f ...

Confusion arises between Bootstrap button plugin and Vue checkbox click event

After incorporating bootstrap.min.js into my Vue app, I noticed that the checkboxes' @click event is no longer triggered. This issue specifically occurs when using bootstrap's button-group with data-toggle="buttons". If I remove bootstrap.min.js, ...

Retrieve the URL redirected by JavaScript without altering the current page using Selenium

Is there a way to extract the URL I am supposed to be redirected to upon clicking a button on a website, without actually being redirected? The button triggers a complex Javascript function and is not a simple hyperlink. click() method doesn't meet my ...

What is the best way to bundle an Express server into an Electron application?

Currently in the process of developing an Electron app using vue-cli-electron-builder. My setup includes a local MySQL database and an Express server. I am wondering how to bundle my Express server with the Electron app? The Express server is used for d ...

Developing a realtime search feature using AJAX and CodeIgniter

Attempting to implement a live search feature in CodeIgniter for the first time. As a newcomer to web development, still in the learning process. Came across a tutorial on how to achieve this here. Struggling with adapting the code from the tutorial to fi ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

Stopping the execution of jQuery().load()

The .load() feature in the jQuery library allows users to selectively load elements from another page, based on specific criteria. I am curious to know if it's feasible to stop or cancel the loading process once initiated. In our program, users can e ...

Concealing the primary div within a Vue child component

Is there a way to conceal the primary div within a Vue application created using Vue-CLI? I attempted adding the display property, but it did not solve the problem. I am attempting to hide it within my Channels component. Here is how my main component lo ...

What is the best way to implement the <b-pagination-nav> component in Bootstrap Vue?

I'm eager to begin using the featured in this guide. However, I'm struggling to figure out how to incorporate the tag into my website. The tutorial's instructions are unclear and as a newcomer, I'm finding it difficult to make it func ...

Increasing the name attribute with Jquery cloning

I'm interested in duplicating the addDriverContent (which is currently functional) and updating the numbers in the name attribute from name="description" to name="description2", name="description3" on the duplicates Additionally, if anyone knows how ...

Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavba ...

Executing search bar capability through the use of AJAX and HTTP requests in JavaScript

I am currently working on implementing a search feature that will locate data based on the user's query. Specifically, I want to create a search bar in my HTML that can search for book titles stored in my database accessible through GET requests. Alth ...

Exploring Three.js on Cordova with WebGL

I am working on developing a mobile app using Three.js on Cordova. While the app runs smoothly on a PC browser, it encounters an issue when trying to create the WebGL context on a Samsung Note 3 device. The specific error message is: THREE.WebGLRenderer ...

Changing an ajax call to an AngularJS HTTP POST conversion

Recently, I've been encountering some issues with calling an existing WCF (non-RESTful) service using $.ajax and the $http service. No matter what I try, I can't seem to get it working properly. The snippet below shows that the service is returni ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

The evaluation of CKEDITOR's execution code

Every time I input my content into CKEDITOR, I receive the following error: "Unexpected token < " This is the code I am using: eval('CKEDITOR.instances.'+ckeditorID+'.insertHtml('+text+')'); The content of variable text ...

Json node tabbing

[ { "idn" : "liquido", "categoria": "Aromatizante Ambiental Liquido", "productos": [ { "nombre": "Canela" }, { "nombre": "Chanel" }, { "nombre": "Citrus" }, ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

Forcing UTF-8 Encoding in JavaScript

I came across this helpful article: While following the advice of many others suggesting to use unescape(encodeURIComponent(srt)), I encountered issues. Attempting to convert the file obtained through XMLHttpRequest did not yield the desired results. Pri ...