如何从ng-change functon调用指令

时间:2018-04-18 06:18:52

标签: javascript angularjs angularjs-directive

我有以下指令,我希望通过传递以下对象来调用此指令。

var datesRangeObject = {};
datesRangeObject.datesRange = 4 * 5;

如何通过传递上述对象来调用,我已经尝试了以下方式,但它无法正常工作。如何将此对象从角度控制器函数传递给指令。

$scope.setmyDirective = function(datesRangeObject) {
  $scope.myDirective = datesRangeObject;
};

app.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: {
      myDirective: '='
    },
    link: function(scope, elem, attrs) {
      // set the initial value of the textbox
      elem.val(scope.myDirective);
      var displayingDays = scope.myDirective.datesRange;
      if (scope.myDirective.selectedDate) {
        var selectedDate = scope.myDirective.selectedDate;
      } else {
        var selectedDate = 0;
      }
      var regionalOptions = {
        "regional": [{
          "es": {
            closeText: "Cerrar",
            prevText: "<Ant",
            nextText: "Sig>",
            currentText: "Hoy",
            monthNames: ["enero", "febrero", "marzo", "abril", "mayo", "junio",
                         "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"
                        ],
            monthNamesShort: ["ene", "feb", "mar", "abr", "may", "jun",
                              "jul", "ago", "sep", "oct", "nov", "dic"
                             ],
            dayNames: ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"],
            dayNamesShort: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
            dayNamesMin: ["D", "L", "M", "M", "J", "V", "S"],
            weekHeader: "Sm",
            dateFormat: "dd/mm/yy",
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ""
          }
        }]
      };
      var pastDays = new Date().getDate() - 1;
      var currentYear = new Date().getFullYear();
      var currentMonth = new Date().getMonth();
      var noOfDays = new Date(currentYear, currentMonth + 2, 0).getDate();
      var nextMonthDays = (noOfDays - pastDays) - 1;
      var minDateRange = selectedDate;
      var maxDateRange = displayingDays + "D"
      var options = {
        changeMonth: true,
        buttonImage: "calendar.gif",
        minDate: minDateRange,
        maxDate: maxDateRange
      };
      elem.datepicker(options);
      elem.datepicker(angular.copy(regionalOptions));
    }
  };
});

该指令与给定日期的日期选择器有关。

1 个答案:

答案 0 :(得分:0)

您需要watch

$scope.$watch( 'datesRangeObject', function() { 
    alert( 'datesRangeObject' ); 
} );
标记脚本中的

<my-directive datesRangeObject="datesRangeObject" />
在你的指令中

scope: {
    test: '@' //on attribute
}