在我的项目中,我使用angularjs开发webapp,我在项目中使用ng-template如下:
<script type="text/ng-template" id = "searchbox.html">
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span><input ng-model = "searchedCity" type="text" class="form-control" id="searchcity" placeholder = "Search City">
</div>
</div>
</script>
<div class="container">
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-lg-2" for="candidatecity">Cities</label>
<div class="col-lg-2">
<select class="form-control" ng-options="city for city in avaiablecities" ng-model="selectedCity" id="candidatecity" ></select>
</div>
<div ng-if="selectedCity=='Others'" ng-include="'searchbox.html'"></div>
<label class="control-label col-lg-2" for="period">Time Period</label>
<div class="col-lg-2">
<select class="form-control" ng-options="period for period in avaiableperiod" ng-model="selectedperiod" id="period"></select>
</div>
<div class="col-lg-2">
<button type="submit" class="btn btn-default" ng-click="clickSendRequest()">Get Data</button>
</div>
</div>
</form>
</div>
城市公共场所列出了一些城市,最后是#34;其他&#34;,如果目标城市不在列表中,用户应自行将城市输入到输入文本框中,由ng-if
控制。它运作正常。
但问题是我无法获取搜索框的用户输入数据。我设置了ng-model = "searchedCity"
指令,但是在下面的JS代码中,我无法获得它的价值。
MyApp.controller('MyCtrl', function($scope,$http) {
$scope.avaiablecities = ["Mexico City","Los Angeles", "Toronto", "Frankfurt", "Milan", "Mumbai", "Chicago", "Paris", "Beijing","Dubai","Sydney","Singapore","Hong Kong","Tokyo","New York","London","Amsterdam","Kuala Lumpur","Brussels","New Delhi","Johannesburg","Others"];
$scope.avaiableperiod = ["Past One Week", "Past One Month","Past One Quarter","Past One Year"];
$scope.clickSendRequest = function() {
// send geocoding request to the API
console.log($scope.selectedCity);
if ($scope.selectedCity == "Others") {
console.log($scope.searchedCity);
} else {
console.log($scope.selectedCity);
}
};
})
console.log($scope.searchedCity)
的输出未定义。
那么问题是什么?
编辑:
经过长时间的调试和很多关于控制器之间通信的谷歌搜索。我找到了根本原因
<div ng-if="selectedCity=='Others'" ng-include="'searchbox.html'"></div>
在上面的标记中,ng-if
和ng-include
用于在页面上实现所需的效果。但它在angularjs中引入了更多关注。由于ng-if
和ng-include
生成更深层次或次级scope
。所以在这种情况下,ng-template是主控制器子代的子代。
所以解决方案是$parent
。所以这样做,可以使它适合我
ng-model = "$parent.$parent.searchedCity"