实时角度js ng-hide不起作用

时间:2016-04-21 11:40:03

标签: javascript angularjs

我有一个html片段,如果变量$ scope.city为空html,我想隐藏它:

<div class="col-lg-12" **ng-hide="{{city === ''}}"**>
     <h1>{{forecast.data.city.country}} ,{{forecast.data.city.name}} </h1>
     <h2>Forcast for : {{city}}</h2>
</div>

<div class="col-lg-8">
    <div class="input-group">
     <span class="input-group-addon" id="basic-addon1">City@</span>
     <input type="text" **ng-model="city"** class="form-control" placeholder="Username" aria-describedby="  basic-addon1">
    </div>
</div>

即使它们被绑定,元素也不会实时隐藏,只有当我使用已经空的$ scope.city变量转到那个页面时,还有一个来自varService的变量城市(我用它来共享多个控制器之间的变量)这里是Angular Code:

app.controller('forecastController', ['$scope','varService','$http', function($scope,varService,$http){

$scope.$watch('city', function() {
    varService.city = $scope.city;
});  
$scope.city = varService.city;
$scope.numOfDays = 2;
$scope.days = 2;
$scope.$watchGroup(['days', 'city'], function() {   

        $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+$scope.city+'&mode=json&appid=e652a2c384655ea24f5b12d2fb84c60f&cnt='+$scope.days+'&units=metric')
    .then(function(data) { $scope.forecast = data; });


});

}]);

那么当我的$ scope.city改变时,如何让ng-hide实时工作?感谢。

3 个答案:

答案 0 :(得分:3)

而不是

ng-hide="{{city === ''}}"

像这样写

ng-hide="city.length===0"

city已绑定到控制器中的$scope,而ng-hide/ng-show需要一个表达式。因此,您不需要使用双花括号({{}})将其评估为真或假,只需提供表达式,如"city.length===0"

答案 1 :(得分:1)

更改代码使用ng-if而不是ng-hide,因为ng-if不会创建元素

<div class="col-lg-12" ng-if="!city.length">
     <h1>{{forecast.data.city.country}} ,{{forecast.data.city.name}} </h1>
     <h2>Forcast for : {{city}}</h2>
</div>

<div class="col-lg-12" ng-hide="city.length">
    <h1>{{forecast.data.city.country}} ,{{forecast.data.city.name}} </h1>
    <h2>Forcast for : {{city}}</h2>
</div>

答案 2 :(得分:1)

试试这个;

ng-hide="city == ''"