Invoking a method stipulated in attributes within an AngularJS directive

I am utilizing a jQuery-ui datapicker and have developed a directive to initialize it (credit: ). Now, I intend to include an HTML attribute that determines the function to call when deciding whether a day should be selectable in the datepicker. How can I achieve this?

Here is the JavaScript code:

//The directive for displaying the jquery-ui datepicker
myApp.directive('datepicker', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ngModelCtrl) {
            $j(function(){
                //Instantiate the datepicker
                element.datepicker({
                    dateFormat:'dd/mm/yy',
                    beforeShowDay:function(date) {
                        //TODO Call the function defined in attrs, passing the date object as an argument
                        theDefinedFunction(date)
                    },
                    onSelect:function (date) {
                        ngModelCtrl.$setViewValue(date);
                        scope.$apply();
                    }
                });
            });
        }
    }
});

Here is the HTML code:

<input type="text" datepicker show-days="myShowDaysFunction()" />

The myShowDaysFunction() needs to be defined in the controller.

(Edit) - Controller function:

$scope.myShowDaysFunction = function(date) {
    console.log("I am called"); //Logs to the console
    console.log(date); //Logs undefined to the console
}

Thank you.

Answer №1

It is important to create a unique scope for your directive and assign the function as a scope variable.

myApp.directive('customDirective', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        scope: {
            customFunction: '&'
        },
        link : function (scope, element, attrs, ngModelCtrl) {
            $j(function(){
                //Initialize the custom datepicker
                element.customDatepicker({
                    dateFormat:'dd/mm/yy',
                    onDaySelection:function(date) {
                        //TODO Call the function defined in the attributes, passing the date object to it
                        scope.customFunction({date: date});
                    },
                    onDateSelect:function (date) {
                        ngModelCtrl.$setViewValue(date);
                        scope.$apply();
                    }
                });
            });
        }
    }
});

Markup

<input type="text" custom-directive custom-function="myCustomFunction(date)" />

Controller Function

$scope.myCustomFunction = function(date) {
    alert(date);
}

Plunker Example

http://plnkr.co/edit/S8bIQhWKFZRaH9criC5r?p=preview

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

How to retrieve the length of data in Angular without relying on ng-repeat?

I am currently working with Angular and facing a challenge where I need to display the total length of an array without using ng-repeat. Here is the situation: I have a default.json file: { { ... "data": [{ "name":"Test", "erro ...

Relocating the Asp.Net WebAPI to its own domain apart from the Asp.Net MVC site in preparation for the AngularJS

We currently have an Asp.Net MVC 5.0 project that utilizes AngularJS for the front end. The project includes a WebAPI Controller within the same project and is deployed on the same website. This application was created using the Individual User Account pro ...

Struggles with loading angular.js controller are arising

My challenge in AngularJS is related to injecting controllers using the ui.router resolve. The issue I'm facing is that the template loads before the controller, causing an error when trying to access the controller. Here's a snippet of my app.js ...

Troubleshooting: Why is the AngularUI Modal dialog malfunctioning

I'm currently working on integrating an angularUI modular dialog into my application. Here is a snippet from my controller.js file: define([ 'app' ], function(app) { app.controller('TeacherClasses', [ '$scope', &apo ...

Showing the date in AngularJSAngularJS can be used to

I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use <span>{{Date.now() | date:'yyyy-MM-dd'}}</span> to display the current date. ...

Refreshing a model using angular.js

I am attempting to reset values in the following way: $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } However, this code ...

Transforming the AngularJS $http GET method to OPTION and including custom headers

var users= $resource('http://myapp.herokuapp.com/users', {}); users.get(); The change in the HTTP GET method to OPTION occurred after implementing a header method. var users= $resource('http://myapp.herokuapp.com/users', {}, { get ...

Using AngularJS directives like ng-hide, ng-show, or ng-if to control visibility based on the active state of

Hello, I am currently developing a shopping cart with three different views: menu, options, and order. The list is generated using ng-repeat from JSON data, with each item in the array having an 'active' field set to false. When an item is added ...

Choosing Between AngularJS and Laravel - Which One is Right for You?

Currently, I am working on developing a web, iOS, and Android app at the same time. I have configured Phalcon to connect with Cassandra database, utilizing it as an API gateway. All requests are made through HTTP and go through the Phalcon application bef ...

Determining the top element displayed in a div: A guide

Looking for an answer on how to determine the top visible element while scrolling? You may find some insights in this post: (Check if element is visible after scrolling). My scenario is slightly different - I have a scrollable div containing multiple ele ...

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...

angular-chart custom tooltip positioning issue

Hello everyone! I'm having trouble fixing the tooltip position when hovering over a point. I've searched through various posts on StackOverflow and have tried all the examples provided in my implementation: https://github.com/chartjs/Chart.js/tr ...

Ways to test and simulate a $timeout function during unit testing

Is there a way to simulate the timeout function being called in this code snippet? $scope.submitRequest = function () { var formData = getData(); $scope.form = JSON.parse(formData); $timeout(function () { $('#submitForm'). ...

Issues with the functionality of the ZeroClipboard Angular plugin

"> I'm fairly new to Angular and currently experimenting with a module called ZeroClipboard. I've made adjustments to my application in order to incorporate the module and configured it as per the demonstration. var app = angular.module(&a ...

Managing URL patterns in AngularJS ui.router: Tips and Tricks

When utilizing the "ui.router" angular JS module, does this mean that the module will have complete control over all URL navigation on the entire page? Currently, I am using the $stateProvider.state method to define URL and State mappings. However, it see ...

Adapting the position of a table row in AngularJS based on the

I need assistance with creating a dynamic table-row that moves to indicate the current time in a table filled with timestamps. <table> <tr ng-repeat="timestamp in timestampArray"> <td>{{timestamp}}</td> </tr> ...

"Exploring the interoperability between Angular's ngSanitize and ngDragDrop

Currently, I am facing compatibility issues within my Angular application when trying to incorporate both ngSanitize and ngDragDrop. The ngDragDrop plugin can be accessed at , while ngSanitize documentation is available at https://docs.angularjs.org/api/ng ...

Guide to deactivating an input field in an angular js smart search dropdown

I'm struggling to figure out how to disable or make an input field read-only for AngularJS. The issue is that users are entering values not available in the dropdown list. Previously, I attempted using the disable property, but this ended up disablin ...

Utilize angular to call a function when navigating

Having an issue with ChartJS while creating a chart using angular. The problem arises when navigating to a new page and then back to the original one, as the JavaScript is not triggered again. Is there a way to automatically invoke a JavaScript function o ...

Despite having multiple AngularJS directives in the HTML, only one appears on the page

If you are interested in working with this repository, you can find it at the following link: https://github.com/nkcraddock/angular-playing-cards In a demo provided within the repository, the code snippet below successfully displays a list of all cards: ...