【问题标题】:AngularJS call callback after update two way binding values in component更新组件中的两种方式绑定值后,AngularJS调用回调
【发布时间】:2016-12-28 09:24:35
【问题描述】:
  myApp.component('example', {
    template: '<button type="button" ng-click="$ctrl.click()">click me</button>',
    bindings: { value: '=', callback: '&' },
    controller: function () {
      this.click = function () {
        this.value = 'clicked';
        this.callback();
      }.bind(this);
    },
  });

  myApp.component('useExample', {
    template: '<example value="$ctrl.value" callback="$ctrl.callback()"></example>',
    controller: function () {
      this.callback = function () { alert(this.value); }.bind(this);
    },
  });

这里有两个组件,而第二个使用第一个。

第一个组件更改this.value,然后调用callback。但是当第二个alert(this.value) 时,它第一次得到空值而不是'clicked'。触发回调时,似乎useExample中的this.value没有更新。

我想获得新价值而不是旧价值。

我试图将example 中的this.callback() 更改为$timeout(function () { this.callback(); }.bind(this), 0) 之类的东西,它可以工作。但我认为应该有更好的方法来做到这一点。

所以,我的问题是在回调中让useExample 读取新的this.value 的最佳方法是什么。

-- 更新 1--

我不想改变给定的界面。

-- 更新 2--

啊哈,我刚搜到这个话题:AngularJS: Parent scope is not updated in directive (with isolated scope) two way binding。这个问题似乎与那个问题重复。我已经阅读过关于这个问题的帖子,看来$timeout 是最好的(?)方式,wt*。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

问题在于,将值从子作用域绑定到父作用域的观察者在调用表达式绑定中的函数之后在微线程(纤程)上执行。

解决方案是在表达式绑定中将值公开为局部变量:

myApp.component('example', {
    template: '<button type="button" ng-click="$ctrl.click()">click me</button>',
    bindings: { 
        callback: '&' 
    },
    controller: function () {
      this.click =  () => {
        this.value = 'clicked';
        //EXPOSE this.value as $value
        this.callback({$value: this.value});
      };
    },
});

在上面的例子中,值暴露为$value

使用暴露的值作为回调函数的参数:

myApp.component('useExample', {
    template: '<example callback="$ctrl.useCallback($value)"></example>',
    controller: function () {
      this.useCallback = (v) => { alert(v); };
    },
});

因为该值是作为回调的参数提供的,所以该值立即可用。

DEMO on JSFiddle

【讨论】:

  • 在回调中传递值不是我想要的。因为它会改变我的组件的接口,并使调用者更加困惑。 (来电者不是我写的)
  • 我只是希望它像&lt;input ng-model="value" ng-change="callback()" /&gt; 那样工作,这对我来说看起来更好,而且似乎更“标准”。
猜你喜欢
  • 2014-04-17
  • 1970-01-01
  • 2014-02-13
  • 2017-01-15
  • 2016-02-27
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多