[英]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.