Angular JS===比较不起作用

Angular JS === comparison not working

本文关键字:不起作用 比较 Angular JS      更新时间:2023-09-26

我正在尝试将从url传递给控制器的值与json文件中的字段进行比较。

galleryItem.html

    <div class="filter-box">
        <ul class="filter list-inline text-center" ng-repeat="gal in ParentData">
            <li><a href="Gallery/({{gal.GalleryLink}})"></a></li>
        </ul>
    </div>
    <div class="container-fluid">
        <div class="row">
            <div class="portfolio-box" ng-repeat="x in data">
                <div class="col-sm-4">
                    <div class="item-img-wrap">
                        <img ng-src={{x.url}} class="img-responsive" alt="">
                        <div class="item-img-overlay">
                            <a href={{x.url}} class="show-image">
                                <span></span>
                            </a>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

更新后的控制器:

controllers.controller('GalleryViewCtrl', function GalleryViewCtrl($scope, $http, $stateParams) {
$scope.pageName = '';
$scope.Description = '';
$scope.GalleryID = $stateParams.id;
$http.get('/data/galleryItems.json')
                .then(function (response) { $scope.ParentData = response.data.galleries });

$http.get('/data/galleryItemImages.json')
                .then(function (response) {
                    $scope.data = response.data.images.galleryIdentifier === $stateParams.id;
                });

});

我验证了将正确的值传递给控制器,这些值是静态的,从json文件传递的数据也是静态的。我放置了一个if语句来检查是否为null。我暂时删除了它,以减少我正在使用的内容。

如果我删除===$stateParams.id,我会返回并正确显示所有图像。

如果我用我知道在列表中的值(4或'4')替换$stateParams.id,我不会得到任何返回。我还尝试了列表中最后一项的值。

调试时没有错误(加载脚本、读取json等),所有值都是正确的。

我对此还是个新手,有太多不同解决方案的文档,这一切都让我感到非常困惑。如果有人有任何想法,我们将不胜感激。

当ajax调用返回一些数据时,您正在将数据加载到$scope.data。我假设您的视图代码甚至在此之前就在调用galleryFiltered。可能是在从方法返回值之前尝试添加null检查。
$scope.galleryFiltered = function () {
   if($scope.data!=null) 
   {
      return $scope.data.galleryIdentifier === $scope.GalleryID;
   }
   return false;
};

请记住,$http服务返回一个promise,因此您的$scope.data将未定义(或保持当前状态),直到$http.get('/data/galleryItemImages.json')返回一个成功回调函数并从响应中为$scope.data分配新值。

如果在promise得到解决之前运行$scope.galleryFiltered(),那么在执行$scope.galleryFiltered()时,您将拥有$scope.data == undefined或存储在$scope.data上的任何数据。