【问题标题】:angular js ng-hide in real time doesn't work实时的角度js ng-hide不起作用
【发布时间】:2016-04-21 11:40:03
【问题描述】:

我有一个 html 的 sn-p,如果变量 $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 代码:

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 实时工作呢?谢谢。

【问题讨论】:

  • 你不必使用{{}},它已经绑定为表达式
  • 将 ng-hide="{{city === ''}} 更改为 ng-hide="!city.length"
  • 谢谢,它成功了,但我还是不明白为什么我不应该使用 {{}} ?
  • 因为 ng-hide 或 ng-click 等下的任何内容都被评估为表达式,请参阅此帖子stackoverflow.com/questions/17878560/…
  • @Mikail 不需要检查 city.length===0,只要加上 !city.length ,0 已经是假了

标签: javascript angularjs


【解决方案1】:

代替

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

这样写

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

city 已经绑定到您的控制器中的$scope,并且ng-hide/ng-show 需要一个表达式。所以你不需要使用双花括号({{}})来评估它的真假,只需像"city.length===0"一样提供表达式。

【讨论】:

    【解决方案2】:

    试试这个;

    ng-hide="city == ''"

    【讨论】:

      【解决方案3】:

      更改您的代码使用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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-17
        • 2019-08-07
        • 1970-01-01
        • 2015-06-29
        • 1970-01-01
        • 1970-01-01
        • 2016-11-24
        • 2014-08-20
        相关资源
        最近更新 更多