Angular JS中包含多个控制器共享的视图逻辑的公共位置

Angular JS Common Place to Contain View Logic Shared by Multiple Controller

本文关键字:视图 位置 共享 JS 包含多 控制器 Angular      更新时间:2023-09-26

我想知道什么是包含如下代码的最佳位置。

if (gameInfo.products[0].product_image_height / gameInfo.products[0].product_image_width > imageRatio) {
        $scope.largeImageCss = "large-image";   
        $scope.sectionType = "vertical_section";
    } else {            
        $scope.largeImageCss = "";
        $scope.sectionType = "horizontal_section";
    }

问题是,正如你所看到的,它修改了视图中的{{largeImageCss}}。

现在我需要相同的逻辑(完全相同的代码)在不同的控制器控制不同的视图。

有没有像helper/mixin这样的东西,我们可以用angular的方式来实现这个目的?

我不认为service, factory, provider是正确的地方,因为它包含当前控制器的$scope操作。

我相信你正在寻找的是在AngularJS中称为服务的东西。虽然AngularJS有内置的服务,如$http, $compile$templateCache,但AngularJS允许你创建自己的自定义服务。

虽然你在你的问题中提到你不觉得服务是控制器的逻辑操作应该发生的地方,我不认为这是一个问题,如果你计划在多个控制器上使用相同的逻辑操作。也许有更有见识的人可以评论一下我的方法是不是"Angular方式"。请看下面的例子:

app.js:

var app = angular.module('app', []);
app.service('sharedProperties', function() {
    return {
        getLargeImageCss: function(info, ratio) {
            if(info.products[0].product_image_height / info.products[0].product_image_width > ratio) {
                return 'large-image';
            }
            else {
                return '';
            }
        },
        getSectionType: function(info, ratio) {
            if(info.products[0].product_image_height / info.products[0].product_image_width > ratio) {
                return 'vertical_section';
            }
            else {
                return 'horizontal_section';
            }
        }
    };
});

controllers.js:

app.controller('controller1', ['$scope', 'sharedProperties', function($scope, sharedProperties) {
    $scope.largeImageCss = sharedProperties.getLargeImageCss(gameInfo, imageRatio);
    $scope.sectionType = sharedProperties.getSectionType(gameInfo, imageRatio);
}]);
app.controller('controller2', ['$scope', 'sharedProperties', function($scope, sharedProperties) {
    $scope.largeImageCss = sharedProperties.getLargeImageCss(gameInfo, imageRatio);
    $scope.sectionType = sharedProperties.getSectionType(gameInfo, imageRatio);
}]);

为了使上面的代码更简洁,因为在两个服务函数中使用了相同的条件,您将getLargeImageCssgetSectionType函数分组为一个getImageInfo函数,该函数在一个对象中返回largeImageCsssectionType