Angular JS中包含多个控制器共享的视图逻辑的公共位置
Angular JS Common Place to Contain View Logic Shared by Multiple Controller
我想知道什么是包含如下代码的最佳位置。
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);
}]);
为了使上面的代码更简洁,因为在两个服务函数中使用了相同的条件,您将getLargeImageCss
和getSectionType
函数分组为一个getImageInfo
函数,该函数在一个对象中返回largeImageCss
和sectionType
。
相关文章:
- float's未返回到移动视图结束后的位置
- 在Appcelerator Titanium中获取视图的相对位置
- 添加视图框时更改鼠标位置
- 如何设置默认视图位置(铯1.6)
- 安卓网页视图位置重定向
- 滚动时修复网格视图标题的位置
- 在网格视图中的页面上弹出 Div 位置
- Famo.us:如何以编程方式对滚动视图的位置进行动画处理
- 固定添加新消息(元素)后的位置视图内容
- 钛 - 安卓:滚动视图滚动位置问题
- AngularJS-使用TweenMax进行位置感知ng视图导航
- Ember.js新模型elem到视图中的第一个位置
- 更改移动视图时图像的位置
- svg对象在网络视图中的位置
- 在BackBone视图中放置JQuery(set:visibility via CSS)的位置
- 如何创建android网络视图以将我的位置共享到网站
- 在backbone.js中为改变主视图中的位置添加子视图
- 嵌套的位置.散列创建子视图/子类别
- 通过重定向返回来刷新视图,同时在Rails中保留滚动位置
- AngularJS ng-map设置视图位置为矩形坐标