angularjs - 如何将变量绑定到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);
});
解决方案
从文档:
AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 拆分为经典和 AngularJS 执行上下文。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等......
您还可以使用$apply()从 JavaScript 输入 AngularJS 执行上下文。请记住,在大多数地方(控制器、服务)
$apply
已经由处理事件的指令为您调用。$apply
仅在实现自定义事件回调或使用第三方库回调时才需要显式调用。
有关更多信息,请参阅AngularJS 开发人员指南 - 与浏览器事件循环集成
推荐阅读
- php - Laravel:markbaker/complex 包和 Composer 的问题
- spring-boot - href 链接在 Widows 环境中不工作,在 Eclipse 中工作正常。春季启动应用程序
- java - 得到“ArrayIndexOutOfBoundsException”,我不知道为什么
- javascript - 将组件导出为默认和常规
- phaser-framework - Phaser 3 切换场景重叠文本
- python - 有没有办法与先验进行多重关联?
- amazon-web-services - 使用 AWS 的全栈项目,运行 yarn ios,出现错误:这些文件都不存在:从 'aws-amplify' 导入 Amplify;从 './aws-exp 导入配置
- optimization - 逻辑回归和 class_weights
- c - 如何为 C 使用 VS Code 调试器?
- java - 模拟输入蒸汽似乎在 Junit 测试的第一个输入上被吃掉了