AngularJS Upgrade(1.5到1.6,1.7)使指令范围绑定未定义

dra*_*arv 10 angularjs angular-directive angular-controller angularjs-1.6

我有以下代码:

angular
  .module('myApp')
  .directive('layout', function () {
      return {
          restrict: 'E',
          template: '<div ng-include="layoutCtrl.pageLayout"></div>',
          controller: 'LayoutController',
          controllerAs: 'layoutCtrl',
          bindToController: true,
          scope: {
              pageLayout: '=',
              pageConfiguration: '=',
              isPreview: '='
          }
      };
  });

angular
  .module('myApp')
  .controller('LayoutController', LayoutController);

function LayoutController($scope, LayoutDTO, LayoutPreviewDTO) {
    var self = this;
    self.layoutDTO = LayoutDTO;
    self.layoutPreviewDTO = LayoutPreviewDTO;
    var test = $scope;

    if(self.isPreview)
        self.layoutModel = new self.layoutPreviewDTO(self.pageConfiguration);
    else
        self.layoutModel = new self.layoutDTO(self.pageConfiguration);
}


<div>
    <layout page-layout="ctrl.layoutTemplateUrl" page-configuration="ctrl.pageConfiguration" is-preview="false"></layout>
</div>
Run Code Online (Sandbox Code Playgroud)

在角度1.5.3版本中,这按预期工作,我的控制器中的变量带有值.现在,自从我升级到1.6.x后,self.pageConfiguration现在未定义.

除角度版本外,没有任何改变.

如何处理传递给控制器​​中指令的值?

geo*_*awg 15

AngularJS团队建议将依赖于范围绑定的控制器代码移动到一个$onInit函数中.

function LayoutController($scope, LayoutDTO, LayoutPreviewDTO) {
    var self = this;
    this.$onInit = function () {
        // bindings will always be available here
        // regardless of the value of `preAssignBindingsEnabled`.
        self.layoutDTO = LayoutDTO;
        self.layoutPreviewDTO = LayoutPreviewDTO;
        var test = $scope;

        if(self.isPreview)
            self.layoutModel = new self.layoutPreviewDTO(self.pageConfiguration);
        else
            self.layoutModel = new self.layoutDTO(self.pageConfiguration);
    };
}
Run Code Online (Sandbox Code Playgroud)

$编译:

由于bcd0d4,默认情况下禁用控制器实例上的预分配绑定.仍然可以将其重新打开,这在迁移期间应该有所帮助.预分配绑定已被弃用,将在以后的版本中删除,因此我们强烈建议您将应用程序迁移到尽快不依赖它.

依赖于存在的绑定的初始化逻辑应放在控制器的$onInit()方法中,保证在分配绑定始终调用该方法.

- AngularJS开发人员指南 - 从v1.5迁移到v1.6 - $ compile


UPDATE

$compileProvider.preAssignBindingsEnabled标志已从AngularJS V1.7中删除.

AngularJS团队强烈建议您将应用程序迁移到尽快不依赖它.AngularJS V1.6将于1月1日上市.

来自Docs:

由于38f8c9,构造函数中不再提供指令绑定.

以前,该$compileProvider.preAssignBindingsEnabled旗帜得到了支持.该标志控制绑定在控制器构造函数内部是否可用或仅在$onInit挂钩中可用.绑定现在在构造函数中不再可用.

要迁移代码:

  • 如果您指定$compileProvider.preAssignBindingsEnabled(true),则需要先迁移代码,以便可以将标记翻转到false.有关如何执行此操作的说明,请参阅 "从1.5迁移到1.6"指南.然后,删除该$compileProvider.preAssignBindingsEnabled(true)语句.

- AngularJS开发人员指南 - 迁移到V1.7 - 编译

注意:

在1月1日,对AngularJS 1.6的支持结束.有关更多信息,请参阅AngularJS MISC - 版本支持状态.


dra*_*arv 1

我想到了:

https://github.com/angular/angular.js/commit/dfb8cf6402678206132e5bc603764d21e0f986ef

现在默认为 false,必须设置为 true $compileProvider.preAssignBindingsEnabled(true);