4

我尝试了什么:

 $routeProvider
     .when('/paintings',
         {
             controller: 'imageController' , 'getPaintingImages'
             templateUrl: 'paintings.html'
         })
     .when('/foods',
         {
             controller: 'imageController' , 'getFoodImages'
             templateUrl: 'food.html'
         })

我想要 getPaintingImages 和 getFoodImages 从工厂获取绘画/食物列表,并希望 imageController 来操作图像。但只有第一个控制器被调用。

早些时候我写了代码来只在 imageController 中获取图像,

myWebsite.controller('imageController', function imageController($scope, getPaintings){

    $scope.images = getPaintings.images();                // but need to make this work for different set of images
    $scope.imageCount = countObjectElements($scope.images);     
    $scope.selectedImage = $scope.images[0];
    $scope.selectedImageIndex = 0;

    $scope.updateSelectedImage = function(img) {        
        $scope.selectedImage = img;
        $scope.selectedImageIndex = $scope.images.indexOf(img);     
    };  
    $scope.updateSelectedImageIndex = function(val) {       

        alert($scope.imageOf);
        if($scope.selectedImageIndex <= 0)
            $scope.selectedImageIndex = $scope.imageCount;

        $scope.selectedImageIndex = ($scope.selectedImageIndex + val) % $scope.imageCount;      
        $scope.selectedImage = $scope.images[$scope.selectedImageIndex];
    };
});

由于我是 angularJS 的初学者,我不确定创建多个控制器是否是重新使用 imageController 的解决方案?如果是,如何做到这一点,如果不是,如何重新使用 imageController 来处理不同的图像集。在函数的情况下,函数的重用通常是通过参数传递。但是在这里我想知道控制器如何在内部调用视图时获取参数?

4

3 回答 3

8

getPaintingImages 和 getFoodImages 正在使用工厂来获取您说的图像。听起来您可以在 routeProvider 中使用类似 resolve: 的东西,以便在调用 imageController 时为它们提供所需的图像。

类似的东西(假设你的 getPaintings 和 getFoods 是服务/工厂和获取图像是返回一个 $promise 解析成图像的东西,即 $http 请求):

$routeProvider
    .when('/paintings', {
        controller: 'imageController',
        templateUrl: 'paintings.html',
        resolve: { 
            images: function($q, getPainting) {
                getPainting.images();
            }
        }
    })
    .when('/foods', {
        controller: 'imageController',
        templateUrl: 'food.html',
        resolve: { 
            images: function($q, getFoods) {
                getFoods.images();
            }
        }
    })

然后你可以访问像这样的图像:

myWebsite.controller('imageController', ['$scope', 'images', function ($scope, images){
    ...
}]);
于 2013-12-29T22:51:12.523 回答
6

如何让 imageController 成为父级:

<body ng-controller="imageController">  
    <div ng-view></div>
</body>
于 2013-10-31T07:14:53.050 回答
2

当您在视图上设置控制器时,控制器请求视图的隔离范围,您不能在同一个视图上有 2 个隔离范围,这会导致错误。您唯一的选择是将控制器应用于父级,或调用imageController第一个控制器内的函数并传递$scope

于 2013-10-31T08:43:24.503 回答