在angularjs中绑定输入并使模型在整个应用程序中持久化
只是想让用户能够在整个应用程序屏幕上从多个点进行搜索 如何保持模型 搜索的HTML如下所示:在angularjs中绑定输入并使模型在整个应用程序中持久化,angularjs,angular-ngmodel,Angularjs,Angular Ngmodel,只是想让用户能够在整个应用程序屏幕上从多个点进行搜索 如何保持模型 搜索的HTML如下所示: <input style="width:80%" ng-model="searchKeyword" id="search" size="70" type="search" results="5" place
<input
style="width:80%"
ng-model="searchKeyword"
id="search"
size="70"
type="search"
results="5"
placeholder="symptôme, maladie, etc."
/>
此代码段位于多个位置,包括一些部分。
目前,听起来在其中一个中输入的值并不是在所有形式中都存在
[EDIT]searchKeyword属于控制器范围
[编辑2]这里有一把小提琴,演示了我想在我的应用程序中解决的问题:
有什么想法吗?您可以使用自定义指令
js
code的种子:
app.directive("search", function(){
var search = {
keyword : ""
}
return {
restrict : "EA",
scope: {},
template : '<input \
style="width:80%" \
ng-model="search.keyword" \
size="70" \
type="search" \
results="5" \
placeholder="symptôme, maladie, etc." \
/>',
link : function(scope, element, attrs){
scope.search = search;
}
}
});
谢谢@artur grzesiak Using directive是我唯一的选择吗?它不是唯一的选择,但它是最优雅的。但是为什么呢?使用指令有什么错?我忘了提到我需要searchKeyword在控制器范围内,因为它在控制器方法中被广泛使用。嗨@artur grziak,我刚刚发布了一个提琴,在它发生的上下文中演示了这个问题。@StéphanedeLuca值是用来存储简单对象的,而对于工厂,您可以利用功能关闭。(除此之外,它们几乎是一样的)。指令可用于价值/工厂/服务之上,以便在整个应用程序中提供一致的“感觉”。在简单输入的情况下,这可能是一种过度使用。我使用它是因为最初不清楚您是否希望使用控制器中的值。
app.controller('MainCtrl', function($scope, searchVal) {
$scope.search = searchVal;
});
app.value("searchVal", {
keyword : "I am in controller - no problem!"
})
app.directive("searchDir", function(searchVal){
return {
restrict : "EA",
scope: {},
template : '<input \
style="width:80%" \
ng-model="search.keyword" \
size="70" \
type="search" \
results="5" \
placeholder="symptôme, maladie, etc." \
/>',
link : function(scope, element, attrs){
scope.search = searchVal;
}
}
});