【发布时间】:2018-07-06 17:46:18
【问题描述】:
AngularJS - 将数据从子组件传递到父组件
我有两个 AngularJS 组件,search 和 form。 search 是 form 的孩子。 search 包含一个文本输入字段。我想发送form search 的输入字段中的值。
我的方法是将函数绑定到search,这会将search 输入字段绑定到form。当 AngularJS 确实尝试绑定这些值时,我得到了错误:
Cannot use 'in' operator to search for '$ctrl' in MyInputValue.
有没有更好的方法来解决我的问题,还是我在代码中的某个地方打错了字?
search.component.js
class SearchComponentController{}
angular
.module('app')
.component('search', {
bindings: {
onSearch: '&'
},
templateUrl: 'search.template.html',
controller: [SearchComponentController]
});
search.template.html
<div>
<input ng-model="$ctrl.keyword" />
<button ng-click="$ctrl.onSearch($ctrl.keyword)">Search</button>
</div>
form.component.js
class FormComponentController {
constructor {}
onSearch(keyword) {
console.log(keyword);
// perform logic
}
}
angular
.module('app')
.component('form', {
templateUrl: 'form.template.html',
controller: [FormComponentController]
});
form.template.html
<div>
<search on-search="$ctrl.onSearch()"></search>
</div>
堆栈跟踪
script.js:14791 TypeError: Cannot use 'in' operator to search for '$ctrl' in MyInputValue
at fn (eval at compile (http://localhost:9005/js/script.js:15642:15), <anonymous>:4:59)
at SearchComponentController.destination.(anonymous function) [as onSearch] (http://localhost:9005/js/script.js:10751:22)
at fn (eval at compile (http://localhost:9005/js/script.js:15642:15), <anonymous>:4:278)
at callback (http://localhost:9005/js/script.js:27463:17)
at Scope.$eval (http://localhost:9005/js/script.js:18533:28)
at Scope.$apply (http://localhost:9005/js/script.js:18632:25)
at HTMLButtonElement.<anonymous> (http://localhost:9005/js/script.js:27468:23)
at defaultHandlerWrapper (http://localhost:9005/js/script.js:3785:11)
at HTMLButtonElement.eventHandler (http://localhost:9005/js/script.js:3773:9)
错误来自 SearchComponentController.destination
case '&':
if (!optional && !hasOwnProperty.call(attrs, attrName)) {
strictBindingsCheck(attrName, directive.name);
}
// Don't assign Object.prototype method to scope
parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
// Don't assign noop to destination if expression is not valid
if (parentGet === noop && optional) break;
destination[scopeName] = function(locals) {
return parentGet(scope, locals);
};
break;
此 switch 语句来自 AngularJS 1.6.8,并从 initializeDirectiveBindings() 调用,它为隔离范围和控制器绑定设置了 $watches。
【问题讨论】:
-
向我们展示错误的整个堆栈跟踪
-
我已经编辑了我的问题以包含我的堆栈跟踪
-
错误来自
SearchComponentController.destination.(anonymous function)。向我们展示该代码。 -
我已经编辑了我的问题以包含代码
SearchComponentController.destination.(anonymous function)(来自 AngularJS 1.6.8。
标签: angularjs components angularjs-components