Bindings on directive with Isolate scope not in scope sometimes

前端 未结 1 790
予麋鹿
予麋鹿 2020-12-12 06:13

So I have a directive with isolate scope and a controllerAs pattern.

    var directive = {
        restric         


        
相关标签:
1条回答
  • 2020-12-12 06:36

    Use the $onInit Life-Cycle Hook to guarantee the timing of bindings:

     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;
            }
        }
    

    From the Docs:

    Initialization logic that relies on bindings being present should be put in the controller's $onInit() method, which is guaranteed to always be called after the bindings have been assigned.

    .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;
        };
      }
    })
    

    — AngularJS Developer Guide - Migrating to V1.6 - $compile

    0 讨论(0)
提交回复
热议问题