Prevent selection of weekend dates in Angular Bootstrap datepicker with a personalized directive

I have integrated the Angular Bootstrap datepicker plugin into my Angular application.

To customize the date pickers in my app, I created a custom directive. In certain places, I need to disable weekends in the date picker. I have added the functions to disable weekend dates within the directive itself.

However, the function to disable weekend dates works perfectly fine when not used within the directive.

This is my custom directive:

app.directive('datePic', function(){
      return {
        restrict: 'E',
        scope: {
          control: "=ngModel",
          min: "=minDate",
          max: "=maxDate",
          disable: "&dateDisabled"
        },
        template: '<div class="col-sm-6"><div class="input-group"><input type="text" class="form-control" datepicker-popup is-open="opened1" ng-model="control" min-date="min" max-date="max" date-disabled="disable" close-text="Close" /><span class="input-group-btn"><button type="button" id="btn2" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button></span></div></div>',
        link: function(scope, elem, attrs){
          scope.open = function($event) {
            $event.preventDefault();
            $event.stopPropagation();
            scope.opened1 = true;
          };

          scope.disabled = function(date, mode) {
            return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
          };

          scope.toggleMin = function() {
            scope.minDate = scope.minDate ? null : new Date();
          };
           scope.toggleMin();
        }
      }
    })

HTML:

<div class="form-group has-feedback">
<label for="inputEmail3" class="col-sm-3 control-label"><span>*</span>From :</label>
<date-pic ng-model="data.leaveFromDate" min-date="minDate" max-date="maxdate" date-disabled="disabled(date, mode)"></date-pic>
</div>

<div class="form-group has-feedback">
<label for="inputEmail3" class="col-sm-3 control-label"><span>*</span>To :</label>
<date-pic ng-model="data.leaveToDate" min-date="data.leaveFromDate" max-date="data.leaveToDate" date-disabled="disabled(date, mode)"></date-pic>
</div>

I am not sure how to pass the date-disabled="disabled(date, mode)" parameter into the directive to dynamically disable weekend dates.

Within the directive, I have defined date-disabled as disable: "&dateDisabled" and used it in the template as date-disabled="disable".

Any advice or recommendations are greatly appreciated.

Thank you in advance.

Answer №1

When defining the disabled function within your custom datePic directive, there is no requirement to pass it in to your custom directive at all.

However, a modification needs to be made to the template within your directive. It should refer to the disabled function defined in the link function of your custom directive. This is how it should appear:

date-disabled="disabled(date, mode)"
.

If you wish to only disable weekends on certain occasions, consider passing a parameter to your custom directive to manage this.

View the modified Jsfiddle with the suggested changes.

Alternatively, if you specifically intend to pass a custom disabled function to your directive, refer to this Jsfiddle where the disabled function is now defined outside the directive in a controller.

Answer №2

<script language="javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>

enter code here

 <div ng-app="myApp" ng-controller="myCntrl">
  From Date: 
    <input type="text" uib-datepicker-popup="{{dateformat}}" min-date="mindate" ng-model="dt" is-open="showdp" 
    date-disabled="disabled(date, mode)" />


    <span>
        <button type="button" class="btn btn-default" ng-click="showcalendar($event)">
            <i class="glyphicon glyphicon-calendar"></i>
        </button>
    </span>
</div>
<script language="javascript">
    angular.module('myApp', ['ngAnimate', 'ui.bootstrap']);
    angular.module('myApp').controller('myCntrl', function ($scope) {
        $scope.today = function () {
            $scope.dt = new Date();
        };
        $scope.mindate = new Date();
        $scope.dateformat="dd/MM/yyyy";
        $scope.today();
        $scope.showcalendar = function ($event) {
            $scope.showdp = true;
        };
        $scope.showdp = false;
        $scope.disabled = function (date, mode) {
return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));

};

    });
</script>
</form>

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

What steps should I follow to utilize a JavaScript dependency following an NPM installation?

After successfully installing Fuse.js using npm, I am having trouble using the dependency in my JavaScript code. The website instructions suggest adding the following code to make it work: var books = [{ 'ISBN': 'A', 'title&ap ...

Vue.js not populating select option tags

I've encountered an issue with my profie.html code that is intended to display division dropdown values using vue.js v-for and {{ val.division_name }}. However, the dropdown is rendering blank values even though there are supposed to be values present ...

Release a stationary element upon scrolling down the page

I have a calculator feature on my website which was coded in php. At the end of this calculator, there is a section that displays the results. While the results div works properly on desktop, I am looking to implement a fix for mobile devices. Specificall ...

Is there a way to display a message box on initial page load only, using JavaScript or jQuery?

I am looking to display a message box only once when a webpage first loads, and then not show it again if the user refreshes the page. The message should appear regardless of whether the user is logged in or not. Is using cookies the only option for achie ...

Utilize specific Angular JS methods just a single time

In my Angular application, I have the following architecture: Index Page -> Shell Page -> User view (User can open subview from here) Every route change in my application goes through the Shell page. There is a function on the Shell page called act ...

How can you connect templates to actions and models in AngularJS directives?

I am currently working on building a custom directive that has presented me with two challenges. Take a look at the template provided below... restrict: 'A', require: '?ngModel', template: '<div>' + ' ...

Using setInterval with Internet Explorer 10

In Internet Explorer 10, the setInterval function does not work properly. I have a web page where, upon form submission, a lengthy process is triggered on the server to download a file. To keep users updated on the progress, I utilize setInterval to repeat ...

How can I show two ng-bind items side by side in Angular JS?

Here is the code snippet: <div id="App2" ng-app="namesList" ng-controller="NamesController" ng-init="firstName='John';lastName='Doe'"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <in ...

"Discover the power of Node.js and AngularJS for creating clean and user-friendly URLs

Is there a way to configure node/angular so that the index.html/app is displayed at example.com instead of example.com/app/index.html#/home? I attempted placing the index.html at the root of the node server, but the URL remains as example.com/index.html#/ ...

Deliver REST-API information on a webpage securely without revealing the API endpoint

I am new to the MEAN stack and have some questions regarding handling unauthenticated REST APIs. When accessing these APIs, I noticed that the end-points are exposed in the JS files which can potentially be exploited by abusers. Is there a way to prevent t ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

What is the best way to include a MongoDB match argument when it is received from the frontend, and to exclude it if it is not provided?

I'm currently working on creating an aggregation in MongoDB using NodeJS. The goal is to add an argument to the MongoDB match function if it exists when the resolver function is called. However, I'm encountering an issue where if no addition is m ...

What is the best way to manage communication with a database in a Node.js application?

I have a specific structure in my Express app: There is a db helper that I use to interact with my MariaDB database Here is the code snippet: var MariaSQL = require('mariasql'); var db = new MariaSQL(); var queries = { getUserByID : &a ...

Can you explain the distinction between using destructuring syntax and an empty parameter when calling a render function?

After writing some code in React, I found using this.props to be too verbose. So, I researched some articles and learned how to approach this issue while coding. class MyComponent extends Component { // the traditional method render() { re ...

"First Screen Scrolling initiates the functionality of the Bottom Sticky Menu

I previously had a sticky navbar positioned at the bottom of the page. It was functioning without any issues, but now I want the sticky navbar to only appear at the bottom of the page when the user scrolls down. .mobile-fixed-res { posit ...

Guide to designing a unique shape in JointJs by combining multiple basic shapes together

Is there a way to combine different shapes in Joint JS, such as creating a custom shape that includes both a rectangle and a circle? I am aware of the path method, but I'm not sure if it is suitable for creating combined shapes like this. ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Having trouble with your angular.jg ng controller functioning properly?

Having trouble getting any content to show up from the media object! The plate object seems to be malfunctioning. <!DOCTYPE html> <html lang="en" ng-app="confusionApp"> <head> <meta charset="utf-8"> <met ...

My Vue.js modal component isn't functioning as expected

I have a Vue JS modal component that is supposed to display all the names typed in the form, but it isn't working. As a newcomer to Vue JS, I'm having trouble understanding why it's not functioning properly. Additionally, I am unable to use ...

How to effectively expose a node controller function for testing in Mocha

Below is the code for my foo-controller.js. module.exports = function(params) { var router = require('express').Router(); var db = params.db var controller = {}; controller.getFoo = function (req, res) { // logic to ret ...