Angular bindToController不工作,可以将对象从一个控制器作用域绑定到另一个控制器作用域

ser*_*rah 8 angularjs

我使用的是Angular 1.5.7版本.

我有一个指令,它将控制器名称和视图名称作为字符串,然后分别调用控制器.

我无法将用户名绑定到上一个控制器的调用控制器,我看到我以前的控制器中可用的值.

请问您可以提出什么问题?

myApp.directive("pendingRequests", function() {
    return {
        restrict: 'E',
        controller: "@",
        name: "controllerName",
        controllerAs: 'pendingReqCtrl',
        scope: {},
        bindToController: {
            username: '=username'
        },
        templateUrl: function(tElement, tAttrs) {
            return tAttrs.templateUrl;
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

Raj*_*M S 13

谢谢 @westor你救了我的一天.我刚刚更新了我的角度并开始得到这个问题,花了很多时间修复它,然后我发现了这个.所以考虑给出一些例子.

在控制器函数中使用$ onInit来绑定范围

controller: function () {
    this.$onInit = function () {

     // your business logic 

    };
};
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,我通过范围绑定

myApp.directive('pendingRequests', function () {
  return {
    scope: {
      item:'='
     },
    bindToController: true,
    controller: controller,
    controllerAs: 'vm',
    controller: function ($scope) {
      console.log(this.item); // doesn't logs 

      this.$onInit = function () {
        console.log(this.item); // logs your other directives object
      };
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

使用 require

myApp.directive('pendingRequests', function () {
  return {
    scope: {},
    bindToController: {},
    controller: controller,
    controllerAs: 'pendingReqCtrl',
    require: {
      parent: '^otherDirective'
    },
    controller: function ($scope) {
      console.log(this.parent); // doesn't logs 

      this.$onInit = function () {
        console.log(this.parent); // logs your item object
      };
    }
  }
});
Run Code Online (Sandbox Code Playgroud)


wes*_*tor 10

您是否尝试使用$ onInit初始化代码?

angularjs doc说:

弃用警告:虽然在调用控制器构造函数之前,非ES6类控制器的绑定当前已绑定到此,但现在不推荐使用此用法.请放置依赖于控制器上$ onInit方法内的绑定的初始化代码.

我更新到1.6.2,我不得不将我的代码放入$ onInit方法来访问绑定.