user6269870
user6269870

Reputation:

How to pass value from controller to a directive

This is my controller

var controller = app.controller('ctrl', ['$scope', function ($scope) {
$scope.months = ["January", "February", "March", "April",
                "May", "June", "July", "August", "September",
                "October", "November", "December"];
}]);

This is my Directive

app.directive('monthDirective', function () {

return {

    restrict: 'A',
    link: function (scope, elem) {

        var fromDate , toDate;
        scope.$watch('fromdate', function (newValue, oldValue) {
            fromDate = new Date(newValue);
            fromDate = moment(newValue, 'YYYY-MM-DD');
            console.log('newValue', newValue)
        });

        scope.$watch('todate', function (newValue, oldValue) {
            toDate = new Date(newValue);
            toDate = moment(newValue, 'YYYY-MM-DD');
            var range = moment.range(fromDate, toDate);
            console.log('toDate', toDate)
            range.by('months',function (moment) {
                moment.toArray('months');
                console.log('I am the array', moment.toArray('months'));
                var mom = moment.toArray('months');
                for (var i = 0; i <= scope.months.length; i++)
                {
                    for (var j = 0; j <= mom.length;j++)
                    {
                        if(scope.months[i] == mom[j][1])
                        {

                        }
                    }
                }

            });
        });

    }
  }
})

I want to get the access of $scope.months(present in my controller) in my directive to do some logic.

Can any one suggest me how to do this?

Upvotes: 0

Views: 95

Answers (2)

E. Abrakov
E. Abrakov

Reputation: 463

By default the directive does't create child scope. So You can access the scope of your controller by default:

app.controller('myController', function ($scope) {
  $scope.test = 'test1';
});
app.directive('myDirective', function () {
  return {
    restrict: 'A',
    link: function (scope, elem) {
        console.log(scope.test)
    }
  }
})

http://plnkr.co/edit/5u2c3mYbLyAX4LIC82l2?p=preview

But NexusDuck is correct. A best practice is to use isolated scope for directive. So you can access the months by passing it in directive attribute

You can also read this. It is very detailed explanation of the scope inheriting.

Upvotes: 2

Robin-Hoodie
Robin-Hoodie

Reputation: 4974

Though you could use a childscope or no scope, a best practice is to use an isolated scope:

app.directive('monthDirective', function () {

return {
    scope: {
      months: '='
    },
    //The rest
  }
});

Usage:

<div month-directive months="months"></div>

Upvotes: 3

Related Questions