升级以在AngularJS的指令中使用$ onInit

时间:2018-08-02 17:18:10

标签: angularjs

我正在从AngularJS 1.4.x升级到1.7.x。该应用程序有很多带有预先指定的绑定的指令(在1.7.x中是不可行的)。我正在寻找以最少的更改进行迁移的最佳方法。

当前代码示例:

angular.module('app')
  .directive('logo', ['ENV', 'utils',
    function main(ENV, utils) {
      return {
        template: '<div><img></div>',
        restrict: 'E',
        replace: true,
        scope: {
          height: '@',
          imgClass: '@',
          imgStyle: '@',
          abbr: '@',
          width: '@',
          abbrObj: '=',
          url: '='
        },
        link: function postLink(scope, element) {

          if (scope.abbr) scope.abbrObj = utils.getObjByAbbr(scope.abbr);
          ...

这显然会引发错误: Error: [$compile:nonassign] Expression 'undefined' in attribute 'abbrObj' used with directive 'logo' is non-assignable!

我尝试了以下操作:

    scope: {
      height: '@',
      imgClass: '@',
      imgStyle: '@',
      abbr: '@',
      width: '@',
      abbrObj: '=',
      url: '='
    },
    controller: function controller() {
      // Initialize
      this.$onInit = function onInit() {
        console.log(this.abbrObj, this.abbr); // results in undefined, undefined
        if (this.abbr) this.abbrObj = utils.getObjByAbbr(this.abbr);
      };
    },
    link: function postLink(scope, element) {
    ...

我不明白为什么Controller中的控制台返回未定义。

我也尝试过使用bindToController: true,但是postLink函数只能访问scope,因此看不到更新的属性。

以最少的更改使用$onInit的最佳方法是什么?

0 个答案:

没有答案