尝试将json数据加载到角度时出错

时间:2014-08-11 13:15:50

标签: angularjs gallery

我正在尝试使用angularjs实现一个简单的照片库,在这里我需要从json文件加载图像并在我的视图文件中显示它们,当我点击一个标签时图像应该显示

控制器

$scope.loadGallery = function(){

        $scope.url = '/dev/images.json';
        $scope.images = [];
        $scope.imageCategories = [];
        $scope.currentImage = {};

        $scope.fetch = function () {
            alert($scope.url);
            $http.get($scope.url).success($scope.handleImagesLoaded);

        }
        function handleImagesLoaded(data, status) {

            $scope.images = data;
            $scope.currentImage = _.first($scope.images);
            $scope.imageCategories = _.uniq(_.pluck($scope.images, 'category'));
        }



        $scope.setCurrentImage = function (image) {
            $scope.currentImage = image;
        };

        $scope.fetch();
    }

HTML

<tab heading="Photos" ng-click="loadGallery()">
    <div id="albumImage">
    asdasd
        <img ng-src="{{currentImage.image}}" alt="{{currentImage.description}}">
    </div>

    <div id="thumbWrapper">
        <ul id="thumbList">
            <li ng-repeat="image in images" ng-click="setCurrentImage(image)">
                <img ng-src="{{image.thumbnail}}" alt="{{image.description}}">
            </li>
        </ul>
    </div>
</tab>

images.json

[
{"category" : "ones",   "image" : "http://localhost:9080/dev/lib/img/contact-img.png", "thumbnail" : "http://localhost:9080/dev/lib/img/contact-img.png", "description" : "Image 01 description"},
{"category" : "twos",   "image" : "http://localhost:9080/dev/lib/img/contact-img2.png", "thumbnail" : "http://localhost:9080/dev/lib/img/contact-img2.png", "description" : "Image 02 description"},
{"category" : "threes", "image" : "http://localhost:9080/dev/lib/img/contact-img3.png", "thumbnail" : "http://localhost:9080/dev/lib/img/contact-img3.png", "description" : "Image 03 description"}

]

但是当我调用loadGallery函数时,我收到了以下错误

TypeError: undefined is not a function
at http://localhost:9080/dev/lib/js/angular.js:7733:11
at wrappedCallback (http://localhost:9080/dev/lib/js/angular.js:11100:81)
at wrappedCallback (http://localhost:9080/dev/lib/js/angular.js:11100:81)
at http://localhost:9080/dev/lib/js/angular.js:11186:26
at Scope.$eval (http://localhost:9080/dev/lib/js/angular.js:12175:28)
at Scope.$digest (http://localhost:9080/dev/lib/js/angular.js:12004:31)
at Scope.$apply (http://localhost:9080/dev/lib/js/angular.js:12279:24)
at done (http://localhost:9080/dev/lib/js/angular.js:7991:45)
at completeRequest (http://localhost:9080/dev/lib/js/angular.js:8196:7)
at XMLHttpRequest.xhr.onreadystatechange     (http://localhost:9080/dev/lib/js/angular.js:8137:11) 

这是什么问题?任何帮助...

1 个答案:

答案 0 :(得分:0)

$scope.handleImagesLoaded未定义,您无法将handleImagesLoaded功能分配到$scope

handleImagesLoaded函数声明后添加此语句,将其分配给$scope

$scope.handleImagesLoaded = handleImagesLoaded;

或者直接在handleImagesLoaded回调中使用.success()功能:

$http.get($scope.url).success(handleImagesLoaded);

希望这有帮助。