我有两个AngularJS组件,search
和form
。 search
是form
的孩子。 search
包含文本输入字段。我想在form
的输入字段中发送search
值。
我的方法是将函数绑定到search
,它会将search
输入字段绑定到form
。当AngularJS尝试绑定这些值时,我收到错误:
Cannot use 'in' operator to search for '$ctrl' in MyInputValue
。
我的解决方案是否有更好的方法,或者我在代码中的哪个地方输了一个错字?
class SearchComponentController{}
angular
.module('app')
.component('search', {
bindings: {
onSearch: '&'
},
templateUrl: 'search.template.html',
controller: [SearchComponentController]
});
<div>
<input ng-model="$ctrl.keyword" />
<button ng-click="$ctrl.onSearch($ctrl.keyword)">Search</button>
</div>
class FormComponentController {
constructor {}
onSearch(keyword) {
console.log(keyword);
// perform logic
}
}
angular
.module('app')
.component('form', {
templateUrl: 'form.template.html',
controller: [FormComponentController]
});
<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)
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()
调用,它为隔离范围和控制器绑定提供$ watch。
答案 0 :(得分:0)
使用1/2路绑定代替&amp;。
bindings: {
onSearch: '<'
},
答案 1 :(得分:0)
angular.module('newsApp').component('newsDetail', {
// ...
bindings: {
onUpdate: '&' // Two-Way binding to Container
}
// ...
var $ctrl = this;
$ctrl.update = function(id, value) {
$ctrl.onUpdate({id: id, value: value}); // Arguments must be an Object
};
<button ng-click="$ctrl.update(2020, 'foobar')">
Upgrade
</button >
2,容器
angular.module('newsApp').component('newsList', {
// ...
$ctrl.updateNews = function(id, value) {
list[id] = value;
};
<detail ... on-update="$ctrl.updateNews (id, value)"> <!-- Pass to component -->
</detail>