Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - Bindings on directive with Isolate scope not in scope sometimes

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

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

and in the controller I init with a call to a REST service using $http that returns a promise.

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

The problem is that if I breakpoint before the init() method vm.something is defined like it should be but in the productsReady function it is undefined.

Is that a normal behaviour? Is the promise resolving code in a different scope?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...