这是我的控制器
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)
的访问权来做一些逻辑。
任何人都可以建议我怎么做吗?
答案 0 :(得分:3)
虽然您可以使用childscope或没有范围,但最佳做法是使用isolated scope:
app.directive('monthDirective', function () {
return {
scope: {
months: '='
},
//The rest
}
});
用法:
<div month-directive months="months"></div>
答案 1 :(得分:2)
默认情况下,该指令不会创建子范围。因此,您可以默认访问控制器的范围:
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
来访问它
您还可以阅读this。这是继承范围的非常详细的解释。