我有以下元素
<div class="list list-inset">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" ng-model="searchTerm" >
</label>
</div>
元素searchTerm可以直接写入输入字段,也可以从控制器添加
<a class="item item-icon-right search-history ng-binding" ng-repeat="item in history" ng-click="insertSearchValue(item)">
a search term
</a>
控制器中的:
$scope.insertSearchValue = function(historyItem){
$scope.searchTerm= historyItem.searchTerm;
}
点击insertSearchValue只在第一时起作用,如果我在输入字段中写了一些内容并将其删除,则点击不再更改该值。
即使$scope.searchTerm
的值实际上已更改。
我假设这与Angular的双向绑定有关,但我尝试了所有相关的内容:($ apply,ngValue,$ setViewValue ...)仍然是同样的问题。
感谢任何提示。
答案 0 :(得分:0)
就像Tom建议的那样,我为您的代码添加了array支持:
编辑现在有一个$scope.history
数组用于列出旧搜索,因此$scope.searchTerm
可以单独用于搜索输入字段。我希望这会有所帮助: - )
var app = angular.module('myApp', [])
.controller('ExampleController', ['$scope',
function($scope) {
//array for history items
$scope.history = ["Books", "CD", "DVD"];
$scope.insertSearchValue = function(historyItem) {
$scope.searchTerm = historyItem;
}
$scope.addNewHistoryItem = function() {
$scope.history.push($scope.searchTerm);
this.clear();
}
$scope.clear = function() {
$scope.searchTerm = "";
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ExampleController">
<div class="list list-inset">
<label class="item item-input">Search
<i class="icon ion-search placeholder-icon"></i>
<input type="text" ng-model="searchTerm">
</label>
<button type="button" ng-click="addNewHistoryItem()">Add new/Search</button>
<button type="button" ng-click="clear()">Clear input</button>
</div>
<br>
Old searches:
<ul ng-repeat="item in history">
<li>
<a class="item item-icon-right search-history ng-binding" ng-click="insertSearchValue(item)" href="javascript:void(0)">
{{item}}
</a>
</li>
</ul>
</div>
答案 1 :(得分:0)
使用ng-model ng-model="data.searchTerm"
时应使用dot。
看看here