ng-change 不适用于我的半自定义日历控件

ng-change isn't working on my semi-custom calendar control

对于我正在开发的应用程序,我可能已经把自己写进了一个角落。

我们在此项目中使用的技术包括 Angular.js 和 UI Bootstrap。我向团队展示的第一件事就是 UI Bootstrap 中的日历系统,它很棒!除了……太复杂了。我被要求构建一个更简单的系统。

我就是这么做的。然而,我遇到了一个障碍。

我们当前应用程序中需要做的一件事是让我们的日历系统引发 ng-change 事件。鉴于 Calendar 系统是一个非标准标签,它只是包装了一个输入字段,我想出了以下代码:

指令:

(function() {
  angular.module('app').directive('calendar', [calendar]);

  function calendar() {
    return {
      restrict: 'E',
      transclude: false,
      scope: {},
      templateUrl: 'calendar.html',
      controller: 'calendarCtrl',
      controllerAs: 'cal',
      compile: function(elem, attrs) {
        var inputName = attrs.inputName;
        var inputElement = elem.find('input');
        inputElement.attr('name', inputName);

        if (attrs.required)
          inputElement.attr('required', true);

        if (attrs.ngChange)
          inputElement.attr('ng-change', attrs.ngChange);

        // Compile returns a Link function!
        return function(scope, iElem, iAttrs, cal) {
          cal.boundProperty = attrs.ngModel;
          cal.bindFromProperty();
        };
      }
    };
  }
})();

You can view the full plunker for this problem here

...但是,当我尝试绑定 ng-change 事件时...

查看:

<body ng-controller="demoCtrl as vm">
  <div class="container">
    <div class="form-group">
      Hello, {{vm.user}}!
    </div>

    <div class="form-group">
      <label>Some Date:</label> 
      <calendar ng-model="vm.someDate" ng-change="vm.dateChanged()" input-name="someDate"></calendar>
    </div>
  </div>
</body>

...更改日历日期只会产生任何结果。 (每次调整日历时,您都应该看到一条非常明显的消息。)

问题:我到底做错了什么,导致 ng-change 无法选择更改?

你不能那样设置 ng-change。它必须由 angular 编译。只需在您的日历模板中的输入上设置一个 ng-change 并让它在您的控制器中调用一个函数。然后该函数将从您的日历指令的属性中调用 ngChange 表达式(使用“&”,而不是 $attrs)。

http://plnkr.co/edit/RNQYcyq46bex0GPqDPRp

在您的指令中,删除更改输入的 ng-change 属性的行并将“&”属性添加到隔离范围定义。

scope: {
    ngChange: '&'
},

在您的日历控制器中,将 ngChange 调用添加到您链接到输入的 ng-change 属性的函数:

function saveDateToBoundProperty() {
        $scope.ngChange();
        [...]
};

您应该阅读有关标记编译($compile 等)和指令隔离范围(以及 @、= 和 &)的内容。

此外,我建议不要将 ngChange 用作自定义指令的属性,因为 ngChange 本身就是一个指令。它可能会导致一些意想不到的行为。例如,您可以改用 dateChange。