簡體   English   中英

如何將值從控制器傳遞給指令

[英]How to pass value from controller to a directive

這是我的控制器

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

這是我的指令

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])
                        {

                        }
                    }
                }

            });
        });

    }
  }
})

我想在我的指令中訪問$scope.months(present in my controller)以執行一些邏輯。

有人可以建議我該怎么做嗎?

盡管可以使用子范圍或不使用范圍,但最佳實踐是使用隔離范圍

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

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

用法:

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

默認情況下,該指令不會創建子范圍。 因此,您可以默認訪問控制器的范圍:

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

但是NexusDuck是正確的。 最佳實踐是對指令使用隔離范圍。 因此,您可以通過在指令屬性中傳遞months來訪問months

您也可以閱讀此內容 它是范圍繼承的非常詳細的說明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM