到目前为止,我的所有AngularJS都在一个页面上,并且在一个控制器中。现在我需要构建一种方法,在所有6个页面中动态提供工具提示 - 当前没有控制器的5个页面,以及当前具有“FoodCtrl”的1个页面。我正在构建的函数将:从tooltips.json文件中读取,通过id找到该页面的正确工具提示,并将工具提示内容插入DOM。
myApp已在所有这些页面上初始化。它是一个小而扁平的层状结构,如下:
--> Profile
--> Information
--> Test (has controller FoodCtrl)
--> Payment
我正在寻找有关正确的Angular练习的建议。我应该使用所需的工具提示行为扩展“FoodCtrl”,并将“FoodCtrl”控制器添加到站点中的其他页面吗?或者,我应该为所有页面创建一个独特的“工具提示”控制器,并以某种方式将其集成到已经具有“FoodCtrl”的页面上?或者,我应该设置一个通用的Tooltip Factory / Service并从“FoodCtrl”引用它以及其他页面上的新特定控制器吗?
答案 0 :(得分:2)
从外部来源获取信息的机制需要提取到单独的服务中,并在需要时注入
有用的链接
http://docs.angularjs.org/guide/dev_guide.services.creating_services
http://docs.angularjs.org/guide/dev_guide.services.injecting_controllers
使用服务的示例
var app = angular.module('myApp', []);
app.service('tooltips', function() {
this.getTooptip = function(pageId) {
...
};
});
function myController($scope, tooltips) {
$scope.pageId = '<pageID>'
$scope.tooltip = tooltips.getTooltip($scope.pageId);
}
答案 1 :(得分:0)
是的,直到现在我已经在一个带控制器的页面上完成了我的所有AngularJS,我对指令是否适用于没有声明控制器的页面感到困惑。答:只要ng-app在那里运行,他们肯定会这样做。所以我将工具提示添加到需要工具提示的每个页面的包装div中,编写了一个名为tooltip的指令来确定哪个页面调用工具提示,并使用服务加载数据。
HTML:
<div class="pagewrapper" tooltip data-title="unique-page-title">
JSON:
[{
"extension": "unique-page-title",
"contents": [
{
"head": "Tooltip heading one",
"content": "information on section 1"
},
{
"head": "Tooltip heading two",
"content": "information on section 2"
}
]
}]
JS:
angular.module('myApp.services', []).service('tooltips', function ($http) {
var requestPromise = $http.get('path/to/tooltips.json').then(function (d) {
return d.data;
});
this.getTooltips = function () {
return requestPromise;
};
});
angular.module('myApp.directives', []).directive('tooltip', function (tooltips, $filter) {
return {
restrict: 'A',
link: function (scope, element, attr) {
var elements = $('.forms .tooltip'),
list = [],
title = attr.title;
//use the promisey service getTooltips to load the tooltips JSON
tooltips.getTooltips().then(function (tips) {
//Do some things to identify the correct place to insert the tooltip content, and insert it.
});
}
};
});