1
votes

I'm trying to access a variable of a controller from a directive but the variable is undefined and I can't figure out why. The variable is undefined immediately on page load which is I'd guess is because the html is loaded before the controller is initialised but I don't understand how it's undefined afterwards when the html is loaded and renderTimetable is called.

angular.module('app')
       .directive('timetable',

function() {
    return {
        restrict: 'E',
        scope: {
            bookings: '=',
            timetableDate: '='
        },
        link: function(scope, elem, attrs) {

                scope.$watch('bookings', function(updatedBookings, unupdatedBookings) {
                    if (typeof updatedBookings !== 'undefined') {
                        console.log(scope.timetableDate); // undefined
                        scope.renderTimetable(updatedBookings);
                    }
                });

                // bookings

                scope.renderTimetable = function(planes) {

                    console.log(scope.timetableDate); // undefined
                }
            };
        }
    };
});

And the directive has attribute set with controller's scope:

<timetable bookings="bookings" timetableDate="timetableDate"></timetable>

The timetableDate model binded like so:

<input readonly datepicker ng-model="timetableDate" value="timetableDate" />

In the controller the variable is set immediately, console.log gets a date string as expected:

...
    function($scope, $http, $location, $interval) {
        $scope.bookingModalVisible = false;
        $scope.timetableDate = new Date().toDateString();
        console.log(timetableDate); // NOT undefined
1

1 Answers

3
votes

Change

<timetable bookings="bookings" timetableDate="timetableDate"></timetable>

to

<timetable bookings="bookings" timetable-date="timetableDate"></timetable>

From Angular docs:

Angular normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).