gpt4 book ai didi

javascript - Angular Directive(指令) : communicating values to controller with ampersand methods

转载 作者:行者123 更新时间:2023-12-03 11:57:48 25 4
gpt4 key购买 nike

我正在尝试了解具有隔离范围的 Angular 指令并与 Controller 进行通信。

我想要创建的是一个简单的可重用搜索组件。该组件具有模型值(查询),并且应该有某种方式向 Controller 指示单击了搜索按钮。

index.html看起来像这样:

<searchbox
ng-model="query"
on-search="search()"
></searchbox>

<p>Current search query: {{query}}</p>

<searchbox>指令看起来像这样:

app.directive('searchbox', function() {
return {
link : function(scope) {
scope.submit = function() {
console.log('Trying to return the query ' + scope.q);
scope.onSearch(scope.q);
}
},
replace : true,
restrict : 'E',
scope : {
'ngModel' : '=q',
'onSearch' : '&'
},
template : ''.concat(
'<form><input ng-model="q" type="text" />',
'<input type="submit" value="Search" ng-click="submit()" />',
'</form>'
)
};
});

主 Controller 如下所示:

app.controller('AppCtrl', function($scope) {
$scope.search = function(query) {
alert('You searched for ' + query);
alert('Search value: ' + $scope.query);
}
});

不幸的是,该查询没有出现在 Controller 中,这都是 search 的结果。回调,并作为 $scope属性(property)。

我用谷歌搜索了一下,但大多数答案似乎都使​​用了 $scope.$eval 的某种变体。 ,或者直接调用 Controller ,这看起来有点像拼凑。

包含上述示例的 Codepen 可以在这里找到:http://codepen.io/hay/pen/Avwjz

任何帮助将不胜感激。

最佳答案

这里有两个问题:

范围定义必须是

'q' : '=ngModel',

左侧是您要在内部使用的名称(您的模板使用q),右侧是属性的名称。

HTML 必须是

on-search="search(query)"

您的submit处理程序是

...
scope.onSearch();

& 表示表达式按原样计算。如果表达式只是 search(),则无论如何都会始终在不带任何参数的情况下调用 search

关于javascript - Angular Directive(指令) : communicating values to controller with ampersand methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com