angularJS 如何从控制器读取指令的变量

How to read variable of a directive from a controller in angularJS

我下载了一个 angularJS 模块,它为我做多日期选择器(由 1 个工厂和 1 个指令组成),并将它们集成到我已经构建的模块中。

即使在我的 angular 模块中添加指令和工厂后它也能正常工作。

如何在我的控制器 SchedulerCtrl 中读取指令中创建的数组 scope.days

1 个工厂、1 个指令和 1 个控制器:

工厂

schedulerApp.factory('multipleDatePickerBroadcast', ['$rootScope', function ($rootScope) {
    var sharedService = {};

    sharedService.calendarId = null;
    sharedService.message = '';

    sharedService.resetOrder = function (calendarId) {
        this.message = 'reset';
        this.calendarId = calendarId;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function () {
        $rootScope.$broadcast('handleMultipleDatePickerBroadcast');
    };

    return sharedService;
}]);

指令

schedulerApp.directive('multipleDatePicker', ['$log', 'multipleDatePickerBroadcast', function ($log, multipleDatePickerBroadcast) {
    "use strict";
    return {
        restrict: 'AE',
        scope: {
           ...
           days: "=",
           ...
        },

        link: function (scope) {
          // Initialization of the variable needed in the controller
          scope.days = scope.days || [];

          // Function to assign some value to scope.days
          scope.toggleDay = function (event, momentDate) {
             ...
             scope.days.push(momentDate);
             ...
          };

        },

        ...
}]);

控制器

schedulerApp.controller('SchedulerCtrl', function($scope, $compile, $timeout, $http, $sce) {

$scope.dbinding = [];

});

感谢任何帮助。谢谢。

HTML

<multiple-date-picker days="dbinding "/>

您可以尝试两种方式绑定并通过模板中的属性访问它。

schedulerApp.directive('multipleDatePicker', ['$log', 'multipleDatePickerBroadcast', function ($log, multipleDatePickerBroadcast) {
    "use strict";
    return {
        restrict: 'AE',
        scope: {
           ...
           days: "=",
           ...
        },