【发布时间】:2017-02-15 23:55:07
【问题描述】:
我目前正在重构 Angular 1.5.8 应用程序中的一些代码以使用组件。
(与本指南中的一些步骤非常相似:https://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html) 基本情况正常。
但是当我需要让我的组件同时更新一个变量并调用一个函数(都从父级绑定)时,我遇到了一个问题。在这种情况下,函数调用似乎发生在变量绑定之前。因此,当方法在父级上执行时,它仍然使用变量的旧内容。
如何确保在方法执行之前变量已更新?
看下面代码中的注释,就是reset()函数的两行。
angular.module('searchfieldComponent', [])
.component('searchfieldComponent', {
templateUrl: "/js/common/components/searchfield.component.tpl.html",
bindings: {
labelText: '@',
searchText: '=',
searchCallback: '&'
},
controllerAs: "vm",
controller: [function() {
var vm = this;
vm.search = function() {
vm.searchCallback();
}
vm.reset = function() {
vm.searchText = null;
// When the method bound to searchCallback executes in the parent,
// the variable bound to searchText has not yet been set to null
// it is still the old value.
vm.searchCallback();
}
}]
});
【问题讨论】:
-
当你使用一个对象在组件之间传递数据,然后修改它的属性时会发生什么?喜欢
searchData: '="; /*...*/ vm.searchData.text = null -
那行得通。谢谢!我想这是因为它始终是同一个对象,所以我以这种方式避免了时间问题。随意将其发布为答案,但我认为包装对象是一种解决方法,而不是最佳解决方案。如果没有更好的答案出现,我会在几天后接受。
标签: angularjs