有时与孤立范围的指令上的绑定有时不在范围内



所以我有指令带有孤立范围scope controlleras 模式。

    var directive = {
        restrict: 'E',
        scope: {
            something: '='
        },
        templateUrl: './App/directiveTemplate.html',
        controller: directiveController,
        controllerAs: 'vm',
        bindToController: true
    }

和在控制器中,我在使用 $ http 返回承诺的情况下呼叫REST服务。

 function directiveController(someService) {
    var vm = this;
    // Here vm.something is defined and bound to the appropriate model set where the directive is used
    init()
    function init() {
        return someService.getProducts()
        .then(productsReady);
        function productsReady(response) {
            vm.products = response;
            //find product using vm.something
            // here vm.something is undefined
           return vm.products;
        }
    }

问题是,如果我在init()方法之前断开vm.something的定义,则像应有的定义,但在productsReady函数中,它是未定义的。

那是正常行为吗?承诺在不同范围中解决代码吗?

使用$onInit生命周期钩子保证绑定时间:

 function directiveController(someService) {
    var vm = this;
    ̶i̶n̶i̶t̶(̶)̶
    this.$onInit = init;
    function init() {
        return someService.getProducts()
        .then(productsReady);
        function productsReady(data) {
            vm.products = data;
           return vm.products;
        }
    }

来自文档:

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

.component('myComponent', {
  bindings: {value: '<'},
  controller: function() {
    this.$onInit = function() {
      // `this.value` will always be initialized,
      // regardless of the value of `preAssignBindingsEnabled`.
      this.doubleValue = this.value * 2;
    };
  }
})

&#8212;AngularJS开发人员指南 - 迁移到v1.6- $ compile

最新更新