在我的项目中,我使用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>
城市组合框中列出了一些城市,最后是“其他”,如果目标城市不在列表中,用户应在输入文本框中自行输入城市,输入文本框由 控制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"