首页 > 解决方案 > 如何将变量绑定到AngularJS中的对象?

问题描述

在下面的代码中,使用 bind(this) 之后,我可以在 configureItemScope 中使用 this.name。

但是,当我调用 updatename() 时 itemScope.item 的值不会更新。它似乎没有绑定到 this.name?

module.controller('ListController', function () {
    this.name = "initial";
    this.delegate = {
        configureItemScope: function (index, itemScope) {
            itemScope.item = this.name;
        }.bind(this)};
    this.updatename = function(){ this.name = "changed"; }.bind(this)
});

单击按钮时,值不会更改: https ://codepen.io/scatman007/pen/PywGor

<ons-page ng-controller="ListController as list">
 <ons-button ng-click="list.change()">click to change</ons-button>
  <ons-list>
    <ons-list-item ons-lazy-repeat="list.delegate">{{ item }}</ons-list-item>
  </ons-list>
</ons-page>

JS

ons.bootstrap()
  .controller('ListController', function() {
   this.delegate = {
      configureItemScope: function(index, itemScope) {itemScope.item = "OLD";},
      countItems: function() {return 0;}
    };

    this.change = function()
     {
      this.delegate.configureItemScope= function(index, itemScope) {
           itemScope.item = "NEW";
      }
      this.delegate.countItems= function() { return 1000;}
     }.bind(this);

  });

标签: angularjsonsen-ui

解决方案


从文档:

AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 拆分为经典和 AngularJS 执行上下文。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等......

您还可以使用$apply()从 JavaScript 输入 AngularJS 执行上下文。请记住,在大多数地方(控制器、服务)$apply已经由处理事件的指令为您调用。$apply仅在实现自定义事件回调或使用第三方库回调时才需要显式调用。

有关更多信息,请参阅AngularJS 开发人员指南 - 与浏览器事件循环集成


推荐阅读